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
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def main():
"""Flask Simple Login Example App""" | Flask Simple Login Example App | main | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def adduser(app, username, password):
"""Add new user with admin access"""
with app.app_context():
create_user(username=username, password=password)
click.echo("user created!") | Add new user with admin access | adduser | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def runserver(app=None, reloader=None, debug=None, host=None, port=None):
"""Run the Flask development server i.e. app.run()"""
debug = debug or app.config.get("DEBUG", False)
reloader = reloader or app.config.get("RELOADER", False)
host = host or app.config.get("HOST", "127.0.0.1")
port = port or app.config.get("PORT", 5000)
app.run(use_reloader=reloader, debug=debug, host=host, port=port) | Run the Flask development server i.e. app.run() | runserver | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def from_current_app(cls, label):
"""Helper to get messages from Flask's current_app"""
return current_app.extensions["simplelogin"].messages.get(label) | Helper to get messages from Flask's current_app | from_current_app | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def default_login_checker(user):
"""user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''}
"""
username = user.get("username")
password = user.get("password")
the_username = os.environ.get(
"SIMPLELOGIN_USERNAME", current_app.config.get("SIMPLELOGIN_USERNAME", "admin")
)
the_password = os.environ.get(
"SIMPLELOGIN_PASSWORD", current_app.config.get("SIMPLELOGIN_PASSWORD", "secret")
)
if username == the_username and password == the_password:
return True
return False | user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''} | default_login_checker | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list"""
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return "simple_logged_in" in session and get_username() in username
return "simple_logged_in" in session | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list | is_logged_in | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def get_username():
"""Get current logged in username"""
return session.get("simple_username") | Get current logged in username | get_username | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return Message.from_current_app("auth_error").format(error), 403 | Return in the first validation error, else return None | login_required.check | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs) | This is for when decorator is @login_required | login_required.simple_decorator | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap | This is for when decorator is @login_required(...) | login_required.decorator | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function])
"""
if function and not callable(function):
raise ValueError(
"Decorator receives only named arguments, "
'try login_required(username="foo")'
)
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return Message.from_current_app("auth_error").format(error), 403
def dispatch(fun, *args, **kwargs):
if basic and request.is_json:
return dispatch_basic_auth(fun, *args, **kwargs)
if is_logged_in(username=username):
return check(must) or fun(*args, **kwargs)
elif is_logged_in():
return Message.from_current_app("access_denied"), 403
else:
SimpleLogin.flash("login_required")
return redirect(url_for("simplelogin.login", next=request.path))
def dispatch_basic_auth(fun, *args, **kwargs):
simplelogin = current_app.extensions["simplelogin"]
auth_response = simplelogin.basic_auth()
if auth_response is True:
return check(must) or fun(*args, **kwargs)
else:
return auth_response
if function:
@wraps(function)
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs)
return simple_decorator
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap
return decorator | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | login_required | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def login_checker(self, f):
"""To set login_checker as decorator:
@simple.login_checher
def foo(user): ...
"""
self._login_checker = f
return f | To set login_checker as decorator:
@simple.login_checher
def foo(user): ... | login_checker | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def basic_auth(self, response=None):
"""Support basic_auth via /login or login_required(basic=True)"""
auth = request.authorization
if auth and self._login_checker(
{"username": auth.username, "password": auth.password}
):
session["simple_logged_in"] = True
session["simple_basic_auth"] = True
session["simple_username"] = auth.username
return response or True
else:
headers = {"WWW-Authenticate": 'Basic realm="Login Required"'}
return "Invalid credentials", 401, headers | Support basic_auth via /login or login_required(basic=True) | basic_auth | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def append_PKCS7_padding(s):
"""return s padded to a multiple of 16-bytes by PKCS7 padding"""
numpads = 16 - (len(s)%16)
return s + numpads*chr(numpads) | return s padded to a multiple of 16-bytes by PKCS7 padding | append_PKCS7_padding | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def strip_PKCS7_padding(s):
"""return s stripped of PKCS7 padding"""
if len(s)%16 or not s:
raise(ValueError("String of len %d can't be PCKS7-padded" % len(s)))
numpads = ord(s[-1])
if numpads > 16:
raise(ValueError("String ending with %r can't be PCKS7-padded" % s[-1]))
return s[:-numpads] | return s stripped of PKCS7 padding | strip_PKCS7_padding | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getSBoxValue(self,num):
"""Retrieves a given S-Box Value"""
return self.sbox[num] | Retrieves a given S-Box Value | getSBoxValue | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getSBoxInvert(self,num):
"""Retrieves a given Inverted S-Box Value"""
return self.rsbox[num] | Retrieves a given Inverted S-Box Value | getSBoxInvert | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def rotate(self, word):
""" Rijndael's key schedule rotate operation.
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
Word is an char list of size 4 (32 bits overall).
"""
return word[1:] + word[:1] | Rijndael's key schedule rotate operation.
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
Word is an char list of size 4 (32 bits overall). | rotate | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getRconValue(self, num):
"""Retrieves a given Rcon Value"""
return self.Rcon[num] | Retrieves a given Rcon Value | getRconValue | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def core(self, word, iteration):
"""Key schedule core."""
# rotate the 32-bit word 8 bits to the left
word = self.rotate(word)
# apply S-Box substitution on all 4 parts of the 32-bit word
for i in range(4):
word[i] = self.getSBoxValue(word[i])
# XOR the output of the rcon operation with i to the first part
# (leftmost) only
word[0] = word[0] ^ self.getRconValue(iteration)
return word | Key schedule core. | core | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def expandKey(self, key, size, expandedKeySize):
"""Rijndael's key expansion.
Expands an 128,192,256 key into an 176,208,240 bytes key
expandedKey is a char list of large enough size,
key is the non-expanded key.
"""
# current expanded keySize, in bytes
currentSize = 0
rconIteration = 1
expandedKey = [0] * expandedKeySize
# set the 16, 24, 32 bytes of the expanded key to the input key
for j in range(size):
expandedKey[j] = key[j]
currentSize += size
while currentSize < expandedKeySize:
# assign the previous 4 bytes to the temporary value t
t = expandedKey[currentSize-4:currentSize]
# every 16,24,32 bytes we apply the core schedule to t
# and increment rconIteration afterwards
if currentSize % size == 0:
t = self.core(t, rconIteration)
rconIteration += 1
# For 256-bit keys, we add an extra sbox to the calculation
if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
for l in range(4): t[l] = self.getSBoxValue(t[l])
# We XOR t with the four-byte block 16,24,32 bytes before the new
# expanded key. This becomes the next four bytes in the expanded
# key.
for m in range(4):
expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
t[m]
currentSize += 1
return expandedKey | Rijndael's key expansion.
Expands an 128,192,256 key into an 176,208,240 bytes key
expandedKey is a char list of large enough size,
key is the non-expanded key. | expandKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def addRoundKey(self, state, roundKey):
"""Adds (XORs) the round key to the state."""
for i in range(16):
state[i] ^= roundKey[i]
return state | Adds (XORs) the round key to the state. | addRoundKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def createRoundKey(self, expandedKey, roundKeyPointer):
"""Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key.
"""
roundKey = [0] * 16
for i in range(4):
for j in range(4):
roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
return roundKey | Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key. | createRoundKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def galois_multiplication(self, a, b):
"""Galois multiplication of 8 bit characters a and b."""
p = 0
for counter in range(8):
if b & 1: p ^= a
hi_bit_set = a & 0x80
a <<= 1
# keep a 8 bit
a &= 0xFF
if hi_bit_set:
a ^= 0x1b
b >>= 1
return p | Galois multiplication of 8 bit characters a and b. | galois_multiplication | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""encrypt `data` using `key`
`key` should be a string of bytes.
returned cipher is a string of bytes prepended with the initialization
vector.
"""
key = map(ord, key)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
data = append_PKCS7_padding(data)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# create a new iv using random data
iv = [ord(i) for i in os.urandom(16)]
moo = AESModeOfOperation()
(mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
# With padding, the original length does not need to be known. It's a bad
# idea to store the original message length.
# prepend the iv.
return ''.join(map(chr, iv)) + ''.join(map(chr, ciph)) | encrypt `data` using `key`
`key` should be a string of bytes.
returned cipher is a string of bytes prepended with the initialization
vector. | encryptData | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""decrypt `data` using `key`
`key` should be a string of bytes.
`data` should have the initialization vector prepended as a string of
ordinal values.
"""
key = map(ord, key)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# iv is first 16 bytes
iv = map(ord, data[:16])
data = map(ord, data[16:])
moo = AESModeOfOperation()
decr = moo.decrypt(data, None, mode, key, keysize, iv)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
decr = strip_PKCS7_padding(decr)
return decr | decrypt `data` using `key`
`key` should be a string of bytes.
`data` should have the initialization vector prepended as a string of
ordinal values. | decryptData | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def generateRandomKey(keysize):
"""Generates a key from random data of length `keysize`.
The returned key is a string of bytes.
"""
if keysize not in (16, 24, 32):
emsg = 'Invalid keysize, %s. Should be one of (16, 24, 32).'
raise(ValueError, emsg % keysize)
return os.urandom(keysize) | Generates a key from random data of length `keysize`.
The returned key is a string of bytes. | generateRandomKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Login = channel.unary_unary(
'/tamuctf.EchoService/Login',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.Logout = channel.unary_unary(
'/tamuctf.EchoService/Logout',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.SendEcho = channel.unary_unary(
'/tamuctf.EchoService/SendEcho',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.ReceiveEcho = channel.unary_unary(
'/tamuctf.EchoService/ReceiveEcho',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
) | Constructor.
Args:
channel: A grpc.Channel. | __init__ | python | sajjadium/ctf-archives | ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | MIT |
def aes_cbc_encrypt(msg: bytes, key: bytes) -> bytes:
"""
Encrypts a message using AES in CBC mode.
Parameters:
msg (bytes): The plaintext message to encrypt.
key (bytes): The encryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The initialization vector (IV) concatenated with the encrypted ciphertext.
"""
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
# Generate a random Initialization Vector (IV)
iv = os.urandom(16)
# Pad the message to be a multiple of the block size (16 bytes for AES)
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_msg = padder.update(msg) + padder.finalize()
# Create the AES cipher in CBC mode
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Encrypt the padded message
ciphertext = encryptor.update(padded_msg) + encryptor.finalize()
# Return IV concatenated with ciphertext
return iv + ciphertext | Encrypts a message using AES in CBC mode.
Parameters:
msg (bytes): The plaintext message to encrypt.
key (bytes): The encryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The initialization vector (IV) concatenated with the encrypted ciphertext. | aes_cbc_encrypt | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | MIT |
def aes_cbc_decrypt(encrypted_msg: bytes, key: bytes) -> bytes:
"""
Decrypts a message encrypted using AES in CBC mode.
Parameters:
encrypted_msg (bytes): The encrypted message (IV + ciphertext).
key (bytes): The decryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The original plaintext message.
"""
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
# Extract the IV (first 16 bytes) and ciphertext (remaining bytes)
iv = encrypted_msg[:16]
ciphertext = encrypted_msg[16:]
# Create the AES cipher in CBC mode
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
# Decrypt the ciphertext
padded_msg = decryptor.update(ciphertext) + decryptor.finalize()
# Remove padding from the decrypted message
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
msg = unpadder.update(padded_msg) + unpadder.finalize()
return msg | Decrypts a message encrypted using AES in CBC mode.
Parameters:
encrypted_msg (bytes): The encrypted message (IV + ciphertext).
key (bytes): The decryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The original plaintext message. | aes_cbc_decrypt | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | MIT |
def place_order():
if 'cart' not in session or not session['cart']:
flash('購物車是空的', 'warning')
return redirect(url_for('cart'))
try:
cursor = db.cursor(dictionary=True)
# 計算訂單金額
total_amount = sum(item['price'] * item['quantity'] for item in session['cart'])
shipping_fee = 100 if total_amount < 3000 else 0
discount_amount = 0
# 處理折扣碼
discount_code = request.form.get('discount_code')
if discount_code:
cursor.execute("""
SELECT * FROM discount_codes
WHERE code = %s
AND is_active = TRUE
AND start_date <= NOW()
AND end_date >= NOW()
AND (usage_limit IS NULL OR used_count < usage_limit)
""", (discount_code,))
discount = cursor.fetchone()
if discount and total_amount >= discount['min_purchase']:
if discount['discount_type'] == 'percentage':
discount_amount = total_amount * (discount['discount_value'] / 100)
else:
discount_amount = discount['discount_value']
# 更新折扣碼使用次數
cursor.execute("""
UPDATE discount_codes
SET used_count = used_count + 1
WHERE id = %s
""", (discount['id'],))
final_amount = total_amount + shipping_fee - discount_amount
# 創建訂單
cursor.execute("""
INSERT INTO orders (
user_id,
total_amount,
shipping_fee,
recipient_name,
recipient_phone,
recipient_email,
shipping_address,
note,
payment_method
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
session.get('user_id'),
final_amount,
shipping_fee,
request.form.get('name'),
request.form.get('phone'),
request.form.get('email'),
request.form.get('address'),
request.form.get('note'),
request.form.get('payment')
))
order_id = cursor.lastrowid
# 保存訂單項目
for item in session['cart']:
# 插入訂單項目
cursor.execute("""
INSERT INTO order_items (
order_id,
product_id,
quantity,
price,
is_custom
) VALUES (%s, %s, %s, %s, %s)
""", (
order_id,
item['id'],
item['quantity'],
item['price'],
item['type'] == 'custom'
))
# 獲取插入的訂單項目 ID
item_id = cursor.lastrowid
# 如果是客製化商品,保存配置
if item['type'] == 'custom' and 'custom_components' in item:
for category, component in item['custom_components'].items():
cursor.execute("""
INSERT INTO order_configurations (
order_item_id,
category_name,
component_name
) VALUES (%s, %s, %s)
""", (
item_id, # 使用正確的訂單項目 ID
category,
component
))
# 如果使用了折扣碼,記錄使用情況
if discount_code and discount:
cursor.execute("""
INSERT INTO discount_usage (
discount_code_id, order_id, user_id
) VALUES (%s, %s, %s)
""", (discount['id'], order_id, session['user_id']))
db.commit()
# 清空購物車
session.pop('cart', None)
flash('訂單已成功建立!', 'success')
return redirect(url_for('order_complete', order_id=order_id))
except Exception as e:
db.rollback()
flash('訂單建立失敗,請重試', 'danger')
print(f"Error: {str(e)}")
return redirect(url_for('checkout')) | , (discount_code,))
discount = cursor.fetchone()
if discount and total_amount >= discount['min_purchase']:
if discount['discount_type'] == 'percentage':
discount_amount = total_amount * (discount['discount_value'] / 100)
else:
discount_amount = discount['discount_value']
# 更新折扣碼使用次數
cursor.execute( | place_order | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def order_detail(order_id):
if 'user_id' not in session:
flash('請先登入', 'danger')
return redirect(url_for('login'))
cursor = db.cursor(dictionary=True)
# 獲取訂單基本信息
cursor.execute("""
SELECT * FROM orders
WHERE id = %s AND user_id = %s
""", (order_id, session['user_id']))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('orders'))
# 獲取訂單項目
cursor.execute("""
SELECT order_items.*, products.name as product_name
FROM order_items
JOIN products ON order_items.product_id = products.id
WHERE order_items.order_id = %s
""", (order_id,))
items = cursor.fetchall()
# 獲取客製化配置
for item in items:
if item['is_custom']:
cursor.execute("""
SELECT category_name, component_name
FROM order_configurations
WHERE order_item_id = %s
""", (item['id'],))
item['configurations'] = cursor.fetchall()
return render_template('order_detail.html', order=order, items=items) | , (order_id, session['user_id']))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('orders'))
# 獲取訂單項目
cursor.execute( | order_detail | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def admin_order_detail(order_id):
cursor = db.cursor(dictionary=True)
# 獲取訂單基本信息
cursor.execute("""
SELECT orders.*, users.username
FROM orders
LEFT JOIN users ON orders.user_id = users.id
WHERE orders.id = %s
""", (order_id,))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('admin_orders'))
# 獲取訂單項目
cursor.execute("""
SELECT order_items.*, products.name as product_name
FROM order_items
JOIN products ON order_items.product_id = products.id
WHERE order_items.order_id = %s
""", (order_id,))
items = cursor.fetchall()
# 獲取客製化配置
for item in items:
if item['is_custom']:
cursor.execute("""
SELECT category_name, component_name
FROM order_configurations
WHERE order_item_id = %s
""", (item['id'],))
item['configurations'] = cursor.fetchall()
return render_template('admin/order_detail.html', order=order, items=items) | , (order_id,))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('admin_orders'))
# 獲取訂單項目
cursor.execute( | admin_order_detail | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def score(sid: str):
"""Score viewer"""
title = db().hget(sid, 'title')
link = db().hget(sid, 'link')
if link is None:
flask.flash("Score not found")
return flask.redirect(flask.url_for('upload'))
return flask.render_template("score.html", sid=sid, link=link.decode(), title=title.decode()) | Score viewer | score | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/web/ScoreShare/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/web/ScoreShare/service/app.py | MIT |
def authenticate(self):
"""Login prompt"""
username = password = b''
with Timeout(30):
# Receive username
self.response(b"Username: ")
username = self.recvline()
if username is None: return
if username in LOGIN_USERS:
password = LOGIN_USERS[username]
else:
self.response(b"No such a user exists.\n")
return
with Timeout(30):
# Receive password
self.response(b"Password: ")
i = 0
while i < len(password):
c = self._conn.recv(1)
if c == b'':
return
elif c != password[i:i+1]:
self.response(b"Incorrect password.\n")
return
i += 1
if self._conn.recv(1) != b'\n':
self.response(b"Incorrect password.\n")
return
self.response(b"Logged in.\n")
self._auth = True
self._user = username | Login prompt | authenticate | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/misc/NetFS_1/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/misc/NetFS_1/server.py | MIT |
def serve(self):
"""Serve files"""
with Timeout(60):
while True:
# Receive filepath
self.response(b"File: ")
filepath = self.recvline()
if filepath is None: return
# Check filepath
if not self.is_admin and \
any(map(lambda name: name in filepath, PROTECTED)):
self.response(b"Permission denied.\n")
continue
# Serve file
try:
f = open(filepath, 'rb')
except FileNotFoundError:
self.response(b"File not found.\n")
continue
except PermissionError:
self.response(b"Permission denied.\n")
continue
except:
self.response(b"System error.\n")
continue
try:
self.response(f.read(MAX_SIZE))
except OSError:
self.response(b"System error.\n")
finally:
f.close() | Serve files | serve | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/misc/NetFS_1/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/misc/NetFS_1/server.py | MIT |
def index():
"""Home"""
return flask.render_template(
"index.html",
is_post=False,
title="Create Paste",
sitekey=RECAPTCHA_SITE_KEY
) | Home | index | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def get_post(id):
"""Read a ticket"""
# Get ticket by ID
content = get_redis_conn(DB_TICKET).get(id)
if content is None:
return flask.abort(404, "not found")
# Check if admin
content = json.loads(content)
key = flask.request.args.get("key")
is_admin = isinstance(key, str) and get_key(id) == key
return flask.render_template(
"index.html",
**content,
is_post=True,
panel=f"""
<strong>Hello admin! Your flag is: {FLAG}</strong><br>
<form id="delete-form" method="post" action="/api/delete">
<input name="id" type="hidden" value="{id}">
<input name="key" type="hidden" value="{key}">
<button id="modal-button-delete" type="button">Delete This Post</button>
</form>
""" if is_admin else "",
url=flask.request.url,
sitekey=RECAPTCHA_SITE_KEY
) | Read a ticket | get_post | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_new():
"""Create a new ticket"""
# Get parameters
try:
title = flask.request.form["title"]
content = flask.request.form["content"]
except:
return flask.abort(400, "Invalid request")
# Register a new ticket
id = b64digest(os.urandom(16))[:16]
get_redis_conn(DB_TICKET).set(
id, json.dumps({"title": title, "content": content})
)
return flask.jsonify({"result": "OK",
"message": "Post created! Click here to see your post",
"action": f"{flask.request.url_root}post/{id}"}) | Create a new ticket | api_new | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_delete():
"""Delete a ticket"""
# Get parameters
try:
id = flask.request.form["id"]
key = flask.request.form["key"]
except:
return flask.abort(400, "Invalid request")
if get_key(id) != key:
return flask.abort(401, "Unauthorized")
# Delete
if get_redis_conn(DB_TICKET).delete(id) == 0:
return flask.jsonify({"result": "NG", "message": "Post not found"})
return flask.jsonify({"result": "OK", "message": "This post was successfully deleted"}) | Delete a ticket | api_delete | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_report():
"""Reoprt an invitation ticket"""
# Get parameters
try:
url = flask.request.form["url"]
reason = flask.request.form["reason"]
recaptcha_token = flask.request.form["g-recaptcha-response"]
except Exception:
return flask.abort(400, "Invalid request")
# Check reCAPTCHA
score = verify_recaptcha(recaptcha_token)
if score == -1:
return flask.jsonify({"result": "NG", "message": "Recaptcha verify failed"})
if score <= 0.3:
return flask.jsonify({"result": "NG", "message": f"Bye robot (score: {score})"})
# Check URL
parsed = urllib.parse.urlparse(url.split('?', 1)[0])
if len(parsed.query) != 0:
return flask.jsonify({"result": "NG", "message": "Query string is not allowed"})
if f'{parsed.scheme}://{parsed.netloc}/' != flask.request.url_root:
return flask.jsonify({"result": "NG", "message": "Invalid host"})
# Parse path
adapter = app.url_map.bind(flask.request.host)
endpoint, args = adapter.match(parsed.path)
if endpoint != "get_post" or "id" not in args:
return flask.jsonify({"result": "NG", "message": "Invalid endpoint"})
# Check ID
if not get_redis_conn(DB_TICKET).exists(args["id"]):
return flask.jsonify({"result": "NG", "message": "Invalid ID"})
key = get_key(args["id"])
message = f"URL: {url}?key={key}\nReason: {reason}"
try:
get_redis_conn(DB_BOT).rpush(
'report', message[:MESSAGE_LENGTH_LIMIT]
)
except Exception:
return flask.jsonify({"result": "NG", "message": "Post failed"})
return flask.jsonify({"result": "OK", "message": "Successfully reported"}) | Reoprt an invitation ticket | api_report | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_new():
"""Add a blog post"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['title'], str)
assert isinstance(data['content'], str)
except:
return flask.abort(400, "Invalid request")
err, post_id = db.add(data['title'], get_username(), data['content'])
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK', 'id': post_id}) | Add a blog post | api_new | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def api_delete():
"""Delete a blog post"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['id'], str)
except:
return flask.abort(400, "Invalid request")
err = db.delete(data['id'])
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK'}) | Delete a blog post | api_delete | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def api_export():
"""Export blog posts"""
db = get_database()
if db is None:
return flask.redirect('/login')
err, blob = db.export_posts(get_username(), get_passhash())
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK', 'export': blob}) | Export blog posts | api_export | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def api_import():
"""Import blog posts"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['import'], str)
except:
return flask.abort(400, "Invalid request")
err = db.import_posts(data['import'], get_username(), get_passhash())
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK'}) | Import blog posts | api_import | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def __iter__(self):
"""Return blog posts sorted by publish date"""
def enumerate_posts(workdir):
posts = []
for path in glob.glob(f'{workdir}/*.json'):
with open(path, "r") as f:
posts.append(json.load(f))
for post in sorted(posts,
key=lambda post: datetime.datetime.strptime(
post['date'], "%Y/%m/%d %H:%M:%S"
))[::-1]:
yield post
return enumerate_posts(self.workdir) | Return blog posts sorted by publish date | __iter__ | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def to_snake(s):
"""Convert string to snake case"""
for i, c in enumerate(s):
if not c.isalnum():
s = s[:i] + '_' + s[i+1:]
return s | Convert string to snake case | to_snake | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def add(self, title, author, content):
"""Add new blog post"""
# Validate title and content
if len(title) == 0: return 'Title is emptry', None
if len(title) > 64: return 'Title is too long', None
if len(content) == 0 : return 'HTML is empty', None
if len(content) > 1024*64: return 'HTML is too long', None
if '{%' in content:
return 'The pattern "{%" is forbidden', None
for brace in re.findall(r"{{.*?}}", content):
if not re.match(r"{{!?[a-zA-Z0-9_]+}}", brace):
return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None
# Save the blog post
now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
post_id = Database.to_snake(title)
data = {
'title': title,
'id': post_id,
'date': now,
'author': author,
'content': content
}
with open(f'{self.workdir}/{post_id}.json', "w") as f:
json.dump(data, f)
return None, post_id | Add new blog post | add | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def read(self, title):
"""Load a blog post"""
post_id = Database.to_snake(title)
if not os.path.isfile(f'{self.workdir}/{post_id}.json'):
return 'The blog post you are looking for does not exist', None
with open(f'{self.workdir}/{post_id}.json', "r") as f:
return None, json.load(f) | Load a blog post | read | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def delete(self, title):
"""Delete a blog post"""
post_id = Database.to_snake(title)
if not os.path.isfile(f'{self.workdir}/{post_id}.json'):
return 'The blog post you are trying to delete does not exist'
os.unlink(f'{self.workdir}/{post_id}.json') | Delete a blog post | delete | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def export_posts(self, username, passhash):
"""Export all blog posts with encryption and signature"""
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'a', zipfile.ZIP_DEFLATED) as z:
# Archive blog posts
for path in glob.glob(f'{self.workdir}/*.json'):
z.write(path)
# Add signature so that anyone else cannot import this backup
z.comment = f'SIGNATURE:{username}:{passhash}'.encode()
# Encrypt archive so that anyone else cannot read the contents
buf.seek(0)
iv = os.urandom(16)
cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv)
encbuf = iv + cipher.encrypt(buf.read())
return None, base64.b64encode(encbuf).decode() | Export all blog posts with encryption and signature | export_posts | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def import_posts(self, b64encbuf, username, passhash):
"""Import blog posts from backup file"""
encbuf = base64.b64decode(b64encbuf)
cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16])
buf = io.BytesIO(cipher.decrypt(encbuf[16:]))
try:
with zipfile.ZipFile(buf, 'r', zipfile.ZIP_DEFLATED) as z:
# Check signature
if z.comment != f'SIGNATURE:{username}:{passhash}'.encode():
return 'This is not your database'
# Extract archive
z.extractall()
except:
return 'The database is broken'
return None | Import blog posts from backup file | import_posts | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/miniblog++/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/miniblog++/app.py | MIT |
def angle_between(p1, p2):
""" Returns the angle in radians between two points """
angle = np.arctan2(p2[1] - p1[1], p2[0] - p1[0])
return angle | Returns the angle in radians between two points | angle_between | python | sajjadium/ctf-archives | ctfs/corCTF/2023/web/msfrognymize/src/anonymize_faces.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2023/web/msfrognymize/src/anonymize_faces.py | MIT |
def step(x: Pair, n: int):
'''Performs n steps to x.'''
return apply(x, calculate(n)) | Performs n steps to x. | step | python | sajjadium/ctf-archives | ctfs/corCTF/2024/crypto/steps/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/crypto/steps/main.py | MIT |
def generate_random_board(n: int) -> list[int]:
"""
Generate a random n x n Lights Out board.
Args:
n (int): The size of the board (n x n).
Returns:
list[int]: A list representing the board, where each element
is either 0 (off) or 1 (on).
"""
board = [random.randint(0, 1) for _ in range(n * n)]
return board | Generate a random n x n Lights Out board.
Args:
n (int): The size of the board (n x n).
Returns:
list[int]: A list representing the board, where each element
is either 0 (off) or 1 (on). | generate_random_board | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def create_vector_representations(n: int) -> list[list[int]]:
"""
Create vector representations for each position on the n x n board.
Args:
n (int): The size of the board (n x n).
Returns:
list[list[int]]: A list of vectors representing the effect of
toggling each light.
"""
vectors = []
for i in range(n * n):
vector = [0] * (n * n)
vector[i] = 1
if i % n != 0:
vector[i - 1] = 1 # left
if i % n != n - 1:
vector[i + 1] = 1 # right
if i >= n:
vector[i - n] = 1 # up
if i < n * (n - 1):
vector[i + n] = 1 # down
vectors.append(vector)
return vectors | Create vector representations for each position on the n x n board.
Args:
n (int): The size of the board (n x n).
Returns:
list[list[int]]: A list of vectors representing the effect of
toggling each light. | create_vector_representations | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def create_augmented_matrix(vectors: list[list[int]],
board: list[int]) -> list[list[int]]:
"""
Create an augmented matrix from the vectors and board state.
Args:
vectors (list[list[int]]): The vector representations.
board (list[int]): The current state of the board.
Returns:
list[list[int]]: The augmented matrix.
"""
matrix = [vec + [board[i]] for i, vec in enumerate(vectors)]
return matrix | Create an augmented matrix from the vectors and board state.
Args:
vectors (list[list[int]]): The vector representations.
board (list[int]): The current state of the board.
Returns:
list[list[int]]: The augmented matrix. | create_augmented_matrix | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def print_board(board: list[int], n: int) -> str:
"""
Generate a string representation of the n x n board.
Args:
board (list[int]): The board state.
n (int): The size of the board (n x n).
Returns:
str: The string representation of the board.
"""
board_string = ""
for i in range(n):
row = ""
for j in range(n):
row += "#" if board[i * n + j] else "."
board_string += row + "\n"
return board_string | Generate a string representation of the n x n board.
Args:
board (list[int]): The board state.
n (int): The size of the board (n x n).
Returns:
str: The string representation of the board. | print_board | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def gauss_jordan_elimination(matrix: list[list[int]]) -> list[list[int]]:
"""
Perform Gauss-Jordan elimination on the given matrix to produce its
Reduced Row Echelon Form (RREF).
Args:
matrix (list[list[int]]): The matrix to be reduced.
Returns:
list[list[int]]: The matrix in RREF.
"""
rows, cols = len(matrix), len(matrix[0])
r = 0
for c in range(cols - 1):
if r >= rows:
break
pivot = None
for i in range(r, rows):
if matrix[i][c] == 1:
pivot = i
break
if pivot is None:
continue
if r != pivot:
matrix[r], matrix[pivot] = matrix[pivot], matrix[r]
for i in range(rows):
if i != r and matrix[i][c] == 1:
for j in range(cols):
matrix[i][j] ^= matrix[r][j]
r += 1
return matrix | Perform Gauss-Jordan elimination on the given matrix to produce its
Reduced Row Echelon Form (RREF).
Args:
matrix (list[list[int]]): The matrix to be reduced.
Returns:
list[list[int]]: The matrix in RREF. | gauss_jordan_elimination | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def is_solvable(matrix: list[list[int]]) -> bool:
"""
Check if the given augmented matrix represents a solvable system.
Args:
matrix (list[list[int]]): The augmented matrix.
Returns:
bool: True if the system is solvable, False otherwise.
"""
rref = gauss_jordan_elimination(matrix)
for row in rref:
if row[-1] == 1 and all(val == 0 for val in row[:-1]):
return False
return True | Check if the given augmented matrix represents a solvable system.
Args:
matrix (list[list[int]]): The augmented matrix.
Returns:
bool: True if the system is solvable, False otherwise. | is_solvable | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def get_solution(board: list[int], n: int) -> list[int] | None:
"""
Get a solution for the Lights Out board if it exists.
Args:
board (list[int]): The current state of the board.
n (int): The size of the board (n x n).
Returns:
list[int] | None: A list representing the solution, or None
if no solution exists.
"""
vectors = create_vector_representations(n)
matrix = create_augmented_matrix(vectors, board)
if not is_solvable(matrix):
return None
rref_matrix = gauss_jordan_elimination(matrix)
# DEBUG
# x = [row[-1] for row in rref_matrix[:n * n]]
# xx = ""
# for i in x:
# xx += "#" if i else "."
# print(xx)
# END DEBUG
return [row[-1] for row in rref_matrix[:n * n]] | Get a solution for the Lights Out board if it exists.
Args:
board (list[int]): The current state of the board.
n (int): The size of the board (n x n).
Returns:
list[int] | None: A list representing the solution, or None
if no solution exists. | get_solution | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def check_solution(board: list[int], solution: list[int], n: int) -> bool:
"""
Check if the given solution solves the Lights Out board.
Args:
board (list[int]): The current state of the board.
solution (list[int]): The proposed solution.
n (int): The size of the board (n x n).
Returns:
bool: True if the solution is correct, False otherwise.
"""
for i in range(n * n):
if solution[i] == 1:
board[i] ^= 1
if i % n != 0:
board[i - 1] ^= 1 # left
if i % n != n - 1:
board[i + 1] ^= 1 # right
if i >= n:
board[i - n] ^= 1 # up
if i < n * (n - 1):
board[i + n] ^= 1 # down
return all(val == 0 for val in board) | Check if the given solution solves the Lights Out board.
Args:
board (list[int]): The current state of the board.
solution (list[int]): The proposed solution.
n (int): The size of the board (n x n).
Returns:
bool: True if the solution is correct, False otherwise. | check_solution | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def main() -> None:
"""
Generates a Lights Out board, sends it to the client,
and checks the client's solution.
"""
print(
"\nWelcome to Lights Out!\n"
"\nThe goal of the game is to turn off all the lights on "
"the board.\n"
"You can toggle any light by entering its position in "
"a string format,\n"
"where # represents ON and . represents OFF.\n"
"Each toggle will also flip the state of its adjacent "
"lights (above, below, left, right).\n"
"Try to turn off all the lights to win!\n"
"\nEnter your solution as a string of #s and .s "
"for ALL board positions, read "
"from left to right, top to bottom (e.g., ..##...#.)\n"
"\nEXAMPLE\n"
"To solve the board:\n\n"
"\t###\n\t#.#\n\t.##\n\n"
"Your solution would be: ..##...#.\n\n\n")
sys.stdout.flush()
while True:
n = random.randint(15, 25)
board = generate_random_board(n)
solution = get_solution(board, n)
if solution is None:
continue
print("\nLights Out Board:\n\n")
print(print_board(board, n))
print("\nYour Solution: ")
sys.stdout.flush()
start_time = time.time()
user_input = input()[:1024].strip()
if time.time() - start_time > 10:
print("\n\nTime out. Generating a new board...\n")
sys.stdout.flush()
continue
user_solution = [1 if c == "#" else 0 for c in user_input]
if len(user_solution) == n * n and check_solution(
board[:], user_solution, n):
print(os.environ.get("FLAG", "corctf{test_flag}"))
sys.stdout.flush()
break
print("\n\nIncorrect solution. Generating a new board...\n")
sys.stdout.flush() | Generates a Lights Out board, sends it to the client,
and checks the client's solution. | main | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False):
"""Mint a new hashcash stamp for 'resource' with 'bits' of collision
20 bits of collision is the default.
'ext' lets you add your own extensions to a minted stamp. Specify an
extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val'
FWIW, urllib.urlencode(dct).replace('&',';') comes close to the
hashcash extension format.
'saltchars' specifies the length of the salt used; this version defaults
8 chars, rather than the C version's 16 chars. This still provides about
17 million salts per resource, per timestamp, before birthday paradox
collisions occur. Really paranoid users can use a larger salt though.
'stamp_seconds' lets you add the option time elements to the datestamp.
If you want more than just day, you get all the way down to seconds,
even though the spec also allows hours/minutes without seconds.
"""
ver = "1"
now = now or time()
if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now))
else: ts = strftime("%y%m%d", localtime(now))
challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars))
return challenge + _mint(challenge, bits) | Mint a new hashcash stamp for 'resource' with 'bits' of collision
20 bits of collision is the default.
'ext' lets you add your own extensions to a minted stamp. Specify an
extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val'
FWIW, urllib.urlencode(dct).replace('&',';') comes close to the
hashcash extension format.
'saltchars' specifies the length of the salt used; this version defaults
8 chars, rather than the C version's 16 chars. This still provides about
17 million salts per resource, per timestamp, before birthday paradox
collisions occur. Really paranoid users can use a larger salt though.
'stamp_seconds' lets you add the option time elements to the datestamp.
If you want more than just day, you get all the way down to seconds,
even though the spec also allows hours/minutes without seconds. | mint | python | sajjadium/ctf-archives | ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | MIT |
def _mint(challenge, bits):
"""Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of requested bits is rounded up to the nearest multiple of 4
"""
counter = 0
hex_digits = int(ceil(bits/4.))
zeros = '0'*hex_digits
while 1:
digest = sha(challenge+hex(counter)[2:]).hexdigest()
if digest[:hex_digits] == zeros:
tries[0] = counter
return hex(counter)[2:]
counter += 1 | Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of requested bits is rounded up to the nearest multiple of 4 | _mint | python | sajjadium/ctf-archives | ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | MIT |
def check(stamp, resource=None, bits=None,
check_expiration=None, ds_callback=None):
"""Check whether a stamp is valid
Optionally, the stamp may be checked for a specific resource, and/or
it may require a minimum bit value, and/or it may be checked for
expiration, and/or it may be checked for double spending.
If 'check_expiration' is specified, it should contain the number of
seconds old a date field may be. Indicating days might be easier in
many cases, e.g.
>>> from hashcash import DAYS
>>> check(stamp, check_expiration=28*DAYS)
NOTE: Every valid (version 1) stamp must meet its claimed bit value
NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
"""
if stamp.startswith('0:'): # Version 0
try:
date, res, suffix = stamp[2:].split(':')
except ValueError:
#ERR.write("Malformed version 0 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
elif type(bits) is not int:
return True
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
elif stamp.startswith('1:'): # Version 1
try:
claim, date, res, ext, rand, counter = stamp[2:].split(':')
except ValueError:
#ERR.write("Malformed version 1 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif type(bits) is int and bits > int(claim):
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
else:
hex_digits = int(floor(int(claim)/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
else: # Unknown ver or generalized hashcash
#ERR.write("Unknown hashcash version: Minimal authentication!\n")
if type(bits) is not int:
return True
elif resource is not None and stamp.find(resource) < 0:
return False
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits) | Check whether a stamp is valid
Optionally, the stamp may be checked for a specific resource, and/or
it may require a minimum bit value, and/or it may be checked for
expiration, and/or it may be checked for double spending.
If 'check_expiration' is specified, it should contain the number of
seconds old a date field may be. Indicating days might be easier in
many cases, e.g.
>>> from hashcash import DAYS
>>> check(stamp, check_expiration=28*DAYS)
NOTE: Every valid (version 1) stamp must meet its claimed bit value
NOTE: Check floor of 4-bit multiples (overly permissive in acceptance) | check | python | sajjadium/ctf-archives | ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | MIT |
def is_doublespent(stamp):
"""Placeholder for double spending callback function
The check() function may accept a 'ds_callback' argument, e.g.
check(stamp, "[email protected]", bits=20, ds_callback=is_doublespent)
This placeholder simply reports stamps as not being double spent.
"""
return False | Placeholder for double spending callback function
The check() function may accept a 'ds_callback' argument, e.g.
check(stamp, "[email protected]", bits=20, ds_callback=is_doublespent)
This placeholder simply reports stamps as not being double spent. | is_doublespent | python | sajjadium/ctf-archives | ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | MIT |
def pick_user(connected, ssh_connection):
"""Pick an available user"""
uids = set(range(MIN_UID, MAX_UID)) - set(connected)
if not uids:
logger.error("no uid available")
sys.exit(1)
uid = sorted(uids)[0]
try:
create_user(uid, uid, ssh_connection)
except FileExistsError:
connected.append(uid)
return pick_user(connected, ssh_connection)
return uid | Pick an available user | pick_user | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | MIT |
def connected_uids():
"""Return a list of connected users."""
# walk /proc/ to retrieve running processes
uids = set([])
for pid in os.listdir("/proc/"):
if not re.match("^[0-9]+$", pid):
continue
try:
uid = os.stat(f"/proc/{pid}").st_uid
except FileNotFoundError:
continue
if uid in range(MIN_UID, MAX_UID):
uids.add(uid)
return list(uids) | Return a list of connected users. | connected_uids | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | MIT |
def device_response(callback, **kwargs):
"""
Stream the response since the communication with the device is not instant.
It prevents concurrent HTTP requests from being blocked.
"""
def generate_device_response(callback, **kwargs):
# force headers to be sent
yield b""
# generate reponse
yield json.dumps(callback(**kwargs)).encode()
return Response(stream_with_context(generate_device_response(callback, **kwargs)), content_type="application/json") | Stream the response since the communication with the device is not instant.
It prevents concurrent HTTP requests from being blocked. | device_response | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py | MIT |
def fortune(self, msg):
""" Generate fortune ticket flavour text. """
nums = [int.from_bytes(msg[i:i+2],'big') for i in range(0,len(msg),2)]
luck = ['']
spce = b'\x30\x00'.decode('utf-16-be')
for num in nums:
if num >= 0x4e00 and num <= 0x9fd6:
luck[-1] += num.to_bytes(2,'big').decode('utf-16-be')
else:
luck += ['']
luck += ['']
maxlen = max([len(i) for i in luck])
for i in range(len(luck)):
luck[i] += spce * (maxlen - len(luck[i]))
card = [spce.join([luck[::-1][i][j] for i in range(len(luck))]) for j in range(maxlen)]
return card | Generate fortune ticket flavour text. | fortune | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | MIT |
def print_card(self, cip, card):
""" Print fortune ticket to terminal. """
upper_hex = long_to_bytes(cip).hex().upper()
fwascii = list(''.join([(ord(i)+65248).to_bytes(2,'big').decode('utf-16-be') for i in list(upper_hex)]))
enclst = [''.join(fwascii[i:i+len(card[0])]) for i in range(0, len(fwascii), len(card[0]))]
# Frame elements
sp = b'\x30\x00'.decode('utf-16-be')
dt = b'\x30\xfb'.decode('utf-16-be')
hl = b'\x4e\x00'.decode('utf-16-be')
vl = b'\xff\x5c'.decode('utf-16-be')
# Print fortune ticket
enclst[-1] += sp*(len(card[0])-len(enclst[-1]))
print()
print(2*sp + dt + hl*(len(card[0])+2) + dt)
print(2*sp + vl + dt + hl*len(card[0]) + dt + vl)
for row in card:
print(2*sp + 2*vl + row + 2*vl)
print(2*sp + vl + dt + hl*len(card[0]) + dt + vl)
for row in enclst:
print(2*sp + vl + sp + row + sp + vl)
print(2*sp + dt + hl*(len(card[0])+2) + dt)
print() | Print fortune ticket to terminal. | print_card | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | MIT |
def parse(polynomial):
'''
TODO: Parse polynomial
For example, parse("x^3 + 2x^2 - x + 1") should return [1,2,-1,1]
''' | TODO: Parse polynomial
For example, parse("x^3 + 2x^2 - x + 1") should return [1,2,-1,1] | parse | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py | MIT |
def __init__(self, maptype, params):
"""Initialise map object"""
if maptype.lower() in ['l','lm','logic']:
self.f = self.__LOGI
elif maptype.lower() in ['e','el','elm','extended logic']:
self.f = self.__EXT_LOGI
else:
raise ValueError('Invalid Map Type.')
try:
self.p = list(params)
except:
self.p = [params] | Initialise map object | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __LOGI(self, x): # <--- p in [3.7, 4]
"""Logistic map"""
return self.p[0] * x * (1 - x) | Logistic map | __LOGI | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __EXT_LOGI(self, x): # <--- p in [2, 4]
"""Extended logistic map"""
if x < 0.5:
return self.__LOGI(x)
else:
return self.p[0] * (x * (x - 1) + 1 / 4) | Extended logistic map | __EXT_LOGI | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def sample(self, x_i, settles, samples):
"""Generates outputs after certain number of settles"""
x = x_i
for _ in range(settles):
x = self.f(x)
ret = []
for _ in range(samples):
x = self.f(x)
ret += [x]
return ret | Generates outputs after certain number of settles | sample | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __init__(self, key=None, iv=None):
"""Initialise Mowhock class object."""
if (key is None) or (len(key) != 64):
key = os.urandom(32).hex()
self.key = key
if (iv is None) or (len(iv) != 16):
iv = os.urandom(8).hex()
self.iv = iv
self.maps = self.map_schedule()
self.buffer_raw = None
self.buffer_byt = None | Initialise Mowhock class object. | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def key_schedule(self):
"""Convert key into 8 round subkeys."""
KL, KR = self.key[:32], self.key[32:]
VL, VR = self.ctr[:8], self.ctr[8:]
HL, HR = [sha256(bytes.fromhex(i)).digest() for i in [VL+KL,VR+KL]]
hlbits, hrbits = ['{:0256b}'.format(int.from_bytes(H,'big')) for H in [HL,HR]]
bitweave = ''.join([hlbits[i]+hrbits[i] for i in range(256)])
subkeys = [int(bitweave[i:i+64],2) for i in range(0,512,64)]
return [self.read_subkey(i) for i in subkeys] | Convert key into 8 round subkeys. | key_schedule | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def map_schedule(self):
"""Convert IV into 8 maps with iv-dependent parameters"""
iv = bytes.fromhex(self.iv)
maps = [
Map('L', iv[0]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[1]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[2]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[3]*(4.00 - 3.86)/255 + 3.86),
Map('E', iv[4]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[5]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[6]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[7]*(4.00 - 3.55)/255 + 3.55),
]
order = self.hop_order(int(self.key[:2],16),8)
return [maps[i] for i in order] | Convert IV into 8 maps with iv-dependent parameters | map_schedule | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def read_subkey(self, subkey):
"""Convert subkey int from key schedule to orbit parameters."""
# Integer to bits
byts = subkey.to_bytes(8, 'big')
bits = ''.join(['{:08b}'.format(i) for i in byts])
# Read key elements
hpsn = int(bits[0:8],2)
seed = float('0.00'+str(int(bits[8:32],2)))
offset = float('0.0000'+str(int(bits[32:48],2)))
settles = int(bits[48:56],2) + 512
orbits = int(bits[56:60],2) + 4
samples = int(bits[60:64],2) + 4
# Processing key elements
hopord = self.hop_order(hpsn,orbits)
x_i = [seed + offset*i for i in hopord]
# Return subkey dictionary
return {
'order' : hopord,
'hpsn' : hpsn,
'seed' : seed,
'offset' : offset,
'x_i' : x_i,
'settles' : settles,
'orbits' : orbits,
'samples' : samples
} | Convert subkey int from key schedule to orbit parameters. | read_subkey | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def hop_order(self, hpsn, orbits):
"""Determine orbit hop order"""
i = 1
ret = []
while len(ret) < orbits:
o = (pow(hpsn,i,256)+i) % orbits
if o not in ret:
ret += [o]
i += 1
return ret | Determine orbit hop order | hop_order | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def ctr_increment(self):
"""Increments IV and reschedules key."""
self.ctr = (int(self.ctr,16) + 1).to_bytes(8, 'big').hex()
self.subkeys = self.key_schedule()
self.fill_buffers() | Increments IV and reschedules key. | ctr_increment | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def fill_buffers(self, save_raw=False):
"""Fills internal buffer with pseudorandom bytes"""
self.buffer_raw = []
self.buffer_byt = []
raw = []
for i in range(8):
settles = self.subkeys[i]['settles']
samples = self.subkeys[i]['samples']
for x_i in self.subkeys[i]['x_i']:
raw += self.maps[i].sample(x_i, settles, samples)
if save_raw:
self.buffer_raw += raw
bitstr = ['{:032b}'.format(int(i*2**53)) for i in raw]
byt = []
for b32 in bitstr:
byt += [int(b32[:8],2) ^ int(b32[16:24],2), int(b32[8:16],2) ^ int(b32[24:32],2)]
self.buffer_byt += bytes(byt) | Fills internal buffer with pseudorandom bytes | fill_buffers | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def encrypt(self, msg):
"""Encrypts a message through the power of chaos"""
# Fill initial buffers
self.ctr = self.iv
self.subkeys = self.key_schedule()
self.fill_buffers()
# Encrypt (increment and refill buffers if necessary)
cip = b''
if type(msg) == str:
msg = bytes.fromhex(msg)
for byt in msg:
try:
cip += bytes( [byt ^ self.buffer_byt.pop(0)] )
except:
self.ctr_increment()
cip += bytes( [byt ^ self.buffer_byt.pop(0)] )
# Return IV and ciphertext
return self.iv + cip.hex() | Encrypts a message through the power of chaos | encrypt | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __init__(self, key):
""" Initialise the bee colony. """
self.fields = self.plant_flowers(key)
self.nectar = None
self.collect() | Initialise the bee colony. | __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 plant_flowers(self, key):
""" Plant flowers around the beehive. """
try:
if type(key) != bytes:
key = bytes.fromhex(key)
return [FlowerField(key[i:i+6]) for i in range(0,36,6)]
except:
raise ValueError('Invalid Key!') | Plant flowers around the beehive. | plant_flowers | 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 collect(self):
""" Collect nectar from the closest flowers. """
A,B,C,D,E,F = [i.flowers for i in self.fields]
self.nectar = [A[2]^^B[4],B[3]^^C[5],C[4]^^D[0],D[5]^^E[1],E[0]^^F[2],F[1]^^A[3]] | Collect nectar from the closest flowers. | collect | 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 swap_petals(F1, F2, i1, i2):
""" Swap the petals of two flowers. """
F1.flowers[i1], F2.flowers[i2] = F2.flowers[i2], F1.flowers[i1] | Swap the petals of two flowers. | cross_breed.swap_petals | 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 cross_breed(self):
""" Cross-breed the outermost bordering flowers. """
def swap_petals(F1, F2, i1, i2):
""" Swap the petals of two flowers. """
F1.flowers[i1], F2.flowers[i2] = F2.flowers[i2], F1.flowers[i1]
A,B,C,D,E,F = self.fields
swap_petals(A,B,1,5)
swap_petals(B,C,2,0)
swap_petals(C,D,3,1)
swap_petals(D,E,4,2)
swap_petals(E,F,5,3)
swap_petals(F,A,0,4) | Cross-breed the outermost bordering flowers. | cross_breed | 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 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 |
Subsets and Splits