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 verify_message(separator, words, signature, ecc_instance): """ Verify the provided signature for the message constructed from words and separator. """ message_bytes = separator.join(word.encode() for word in words) + separator message_int = int.from_bytes(message_bytes, byteorder='big') if ecc_instance.verify(message_int, signature): display_flag() sys.exit(0) else: print("Verification failed.") sys.exit(0)
Verify the provided signature for the message constructed from words and separator.
verify_message
python
sajjadium/ctf-archives
ctfs/PatriotCTF/2024/crypto/Textbook_Schnorr_right/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/PatriotCTF/2024/crypto/Textbook_Schnorr_right/chall.py
MIT
def is_safe_username(username): """Check if the username is alphanumeric and less than 20 characters.""" return username.isalnum() and len(username) < 20
Check if the username is alphanumeric and less than 20 characters.
is_safe_username
python
sajjadium/ctf-archives
ctfs/PatriotCTF/2024/web/Impersonate/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/PatriotCTF/2024/web/Impersonate/app.py
MIT
def main(): """Handle the main page where the user submits their username.""" if request.method == 'GET': return render_template('index.html') elif request.method == 'POST': username = request.values['username'] password = request.values['password'] if not is_safe_username(username): return render_template('index.html', error='Invalid username') if not password: return render_template('index.html', error='Invalid password') if username.lower().startswith('admin'): return render_template('index.html', error='Don\'t try to impersonate administrator!') if not username or not password: return render_template('index.html', error='Invalid username or password') uid = uuid.uuid5(secret, username) session['username'] = username session['uid'] = str(uid) return redirect(f'/user/{uid}')
Handle the main page where the user submits their username.
main
python
sajjadium/ctf-archives
ctfs/PatriotCTF/2024/web/Impersonate/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/PatriotCTF/2024/web/Impersonate/app.py
MIT
def user_page(uid): """Display the user's session page based on their UUID.""" try: uid = uuid.UUID(uid) except ValueError: abort(404) session['is_admin'] = False return 'Welcome Guest! Sadly, you are not admin and cannot view the flag.'
Display the user's session page based on their UUID.
user_page
python
sajjadium/ctf-archives
ctfs/PatriotCTF/2024/web/Impersonate/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/PatriotCTF/2024/web/Impersonate/app.py
MIT
def admin_page(): """Display the admin page if the user is an admin.""" if session.get('is_admin') and uuid.uuid5(secret, 'administrator') and session.get('username') == 'administrator': return flag else: abort(401)
Display the admin page if the user is an admin.
admin_page
python
sajjadium/ctf-archives
ctfs/PatriotCTF/2024/web/Impersonate/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/PatriotCTF/2024/web/Impersonate/app.py
MIT
def banner(): os.system("clear") print( ''' ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ \u258f ___ ___ _ ___ _ _ ___ \u258f \u258f | _ ) _ \ /_\ |_ _| \| | __|/\_ \u258f \u258f | _ \ / / _ \ | || .` | _|> < \u258f \u258f |___/_|_\/_/ \_\___|_|\_|_| \/ \u258f \u258f ___ ___ ___ ___ ___ _ __ __ __ __ ___ _ _ ___ \u258f \u258f | _ \ _ \/ _ \ / __| _ \ /_\ | \/ | \/ |_ _| \| |/ __| \u258f \u258f | _/ / (_) | (_ | / / _ \| |\/| | |\/| || || .` | (_ | \u258f \u258f |_| |_|_\\\___/ \___|_|_\/_/ \_\_| |_|_| |_|___|_|\_|\___| \u258f \u258f \u258f β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”''' )
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ \u258f ___ ___ _ ___ _ _ ___ \u258f \u258f | _ ) _ \ /_\ |_ _| \| | __|/\_ \u258f \u258f | _ \ / / _ \ | || .` | _|> < \u258f \u258f |___/_|_\/_/ \_\___|_|\_|_| \/ \u258f \u258f ___ ___ ___ ___ ___ _ __ __ __ __ ___ _ _ ___ \u258f \u258f | _ \ _ \/ _ \ / __| _ \ /_\ | \/ | \/ |_ _| \| |/ __| \u258f \u258f | _/ / (_) | (_ | / / _ \| |\/| | |\/| || || .` | (_ | \u258f \u258f |_| |_|_\\\___/ \___|_|_\/_/ \_\_| |_|_| |_|___|_|\_|\___| \u258f \u258f \u258f β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”β–”
banner
python
sajjadium/ctf-archives
ctfs/bi0sCTF/2024/misc/bfs/test.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/bi0sCTF/2024/misc/bfs/test.py
MIT
def Z2kDH_init(private_exponent): """ Computes the public result by taking the generator 5 to the private exponent, then removing the last 2 bits private_exponent must be a positive integer less than 2^256 """ return pow(5, private_exponent, modulus) // 4
Computes the public result by taking the generator 5 to the private exponent, then removing the last 2 bits private_exponent must be a positive integer less than 2^256
Z2kDH_init
python
sajjadium/ctf-archives
ctfs/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py
MIT
def Z2kDH_exchange(public_result, private_exponent): """ Computes the shared secret by taking the sender's public result to the receiver's private exponent, then removing the last 2 bits public_result must be a non-negative integer less than 2^256 private_exponent must be a positive integer less than 2^256 """ return pow(public_result * 4 + 1, private_exponent, modulus) // 4
Computes the shared secret by taking the sender's public result to the receiver's private exponent, then removing the last 2 bits public_result must be a non-negative integer less than 2^256 private_exponent must be a positive integer less than 2^256
Z2kDH_exchange
python
sajjadium/ctf-archives
ctfs/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WolvCTF/2023/crypto/Z2kDH/Z2kDH.py
MIT
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ezsqli.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
Run administrative tasks.
main
python
sajjadium/ctf-archives
ctfs/TPCTF/2023/web/ezsqli/manage.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TPCTF/2023/web/ezsqli/manage.py
MIT
def oblivious(self): P = getPrime(384) Q = getPrime(384) N = P * Q d = pow(0x10001, -1, (P-1)*(Q-1)) x1 = random.randint(0, N-1) x2 = random.randint(0, N-1) x3 = random.randint(0, N-1) print("Mercury: It's boring to directly give you prime back, I'll give you the prime thrugh oblivious transfer! Here are the parameters: ") print("") print(f"N = {N}") print(f"x1 = {x1}") print(f"x2 = {x2}") print(f"x3 = {x3}") """ Pick a random r and compute v = r**65537 + x1/x2/x3 If you added x1/x2/x3, then you can retrieve p/q/r by calculating c1/c2/c3 - k % n """ v = int(input("Which one is your prime? Gimme your response: ")) k1 = pow(v-x1, d, N) k2 = pow(v-x2, d, N) k3 = pow(v-x3, d, N) c1 = (k1+self.p) % N c2 = (k2+self.q) % N c3 = (k3+self.r) % N print("") print(f"c1 = {c1}") print(f"c2 = {c2}") print(f"c3 = {c3}")
Pick a random r and compute v = r**65537 + x1/x2/x3 If you added x1/x2/x3, then you can retrieve p/q/r by calculating c1/c2/c3 - k % n
oblivious
python
sajjadium/ctf-archives
ctfs/idekCTF/2023/crypto/decidophobia/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/idekCTF/2023/crypto/decidophobia/server.py
MIT
def test_jpeg1(h, f): """JPEG data in JFIF format""" if b'JFIF' in h[:23]: return 'jpeg'
JPEG data in JFIF format
test_jpeg1
python
sajjadium/ctf-archives
ctfs/idekCTF/2021/web/saas/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/idekCTF/2021/web/saas/app.py
MIT
def test_jpeg2(h, f): """JPEG with small header""" if len(h) >= 32 and 67 == h[5] and h[:32] == JPEG_MARK: return 'jpeg'
JPEG with small header
test_jpeg2
python
sajjadium/ctf-archives
ctfs/idekCTF/2021/web/saas/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/idekCTF/2021/web/saas/app.py
MIT
def test_jpeg3(h, f): """JPEG data in JFIF or Exif format""" if h[6:10] in (b'JFIF', b'Exif') or h[:2] == b'\xff\xd8': return 'jpeg'
JPEG data in JFIF or Exif format
test_jpeg3
python
sajjadium/ctf-archives
ctfs/idekCTF/2021/web/saas/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/idekCTF/2021/web/saas/app.py
MIT
def index(): if request.method == 'POST': if not request.form['q']: return render_template_string(error_page) if len(request.form) > 1: return render_template_string(error_page) query = request.form['q'].lower() if '{' in query and any([bad in query for bad in blacklist]): return render_template_string(error_page) if len(query) > 256: return render_template_string(error_page) page = \ ''' {{% extends "layout.html" %}} {{% block body %}} <center> <section class="section"> <div class="container"> <h1 class="title">You have entered the raffle!</h1> <ul class=flashes> <label>Hey {}! We have received your entry! Good luck!</label> </ul> </br> </div> </section> </center> {{% endblock %}} '''.format(query) elif request.method == 'GET': page = \ ''' {% extends "layout.html" %} {% block body %} <center> <section class="section"> <div class="container"> <h1 class="title">Welcome to the idekCTF raffle!</h1> <p>Enter your name below for a chance to win!</p> <form action='/' method='POST' align='center'> <p><input name='q' style='text-align: center;' type='text' placeholder='your name' /></p> <p><input value='Submit' style='text-align: center;' type='submit' /></p> </form> </div> </section> </center> {% endblock %} ''' return render_template_string(page)
{{% extends "layout.html" %}} {{% block body %}} <center> <section class="section"> <div class="container"> <h1 class="title">You have entered the raffle!</h1> <ul class=flashes> <label>Hey {}! We have received your entry! Good luck!</label> </ul> </br> </div> </section> </center> {{% endblock %}} '''.format(query) elif request.method == 'GET': page = \
index
python
sajjadium/ctf-archives
ctfs/idekCTF/2021/web/jinjail/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/idekCTF/2021/web/jinjail/app.py
MIT
def exec_poisonous(code): """Makes sure your code is safe to run""" def no_import(name, *args, **kwargs): raise ImportError("Don't ask another snake for help!") code += "\nresults = printed" byte_code = compile_restricted( code, filename="<string>", mode="exec", ) policy_globals = {**safe_globals, **utility_builtins} policy_globals['__builtins__']['__metaclass__'] = type policy_globals['__builtins__']['__name__'] = type policy_globals['__builtins__']['__import__'] = no_import policy_globals['_getattr_'] = Guards.safer_getattr policy_globals['_getiter_'] = Eval.default_guarded_getiter policy_globals['_getitem_'] = Eval.default_guarded_getitem policy_globals['_write_'] = Guards.full_write_guard policy_globals['_print_'] = PrintCollector policy_globals['_iter_unpack_sequence_'] = Guards.guarded_iter_unpack_sequence policy_globals['_unpack_sequence_'] = Guards.guarded_unpack_sequence policy_globals['enumerate'] = enumerate exec(byte_code, policy_globals, None) return policy_globals["results"]
Makes sure your code is safe to run
exec_poisonous
python
sajjadium/ctf-archives
ctfs/UIUCTF/2023/pwn/Rattler_Read/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UIUCTF/2023/pwn/Rattler_Read/main.py
MIT
def check_flag(flag_guess: str): """REDACTED FOR PRIVACY"""
REDACTED FOR PRIVACY
check_flag
python
sajjadium/ctf-archives
ctfs/UIUCTF/2024/misc/Push_and_Pickle/chal_redacted.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UIUCTF/2024/misc/Push_and_Pickle/chal_redacted.py
MIT
def get_s_from_x(x,a,b,p): """ s is the same as y**2 """ return (x**3 + a*x + b) % p
s is the same as y**2
get_s_from_x
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
MIT
def has_QRp(a, p): """ Euler's criterion x**2 = a % p -> does x exist? not all a's in p have an x """ if p % 2 == 0: return False return pow(a, (p-1) >> 1, p) == 1
Euler's criterion x**2 = a % p -> does x exist? not all a's in p have an x
has_QRp
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
MIT
def get_y_from_s(s,p): """ Tonellis Algorithm """ if not has_QRp(s, p): return 0 if (p % 4 == 3): return pow(s, (p + 1) / 4, p) h = 2 while (has_QRp(h, p)): h += 1 s_exp = (p-1) >> 1 h_exp = p-1 h_exp_half = (p-1) >> 1 res = (pow(s,s_exp, p) * pow(h, h_exp, p)) % p; # finished when (s_exp is odd) and (s^s_exp * h^h_exp == 1 (mod p)) while (s_exp % 2 == 0 or res != 1) : if (res == 1): s_exp = s_exp >> 1 h_exp = h_exp >> 1 else: h_exp = h_exp + h_exp_half res = (pow(s, s_exp, p) * pow(h, h_exp, p)) % p # pow(s, (s_exp + 1) / 2, p) * pow(h, (h_exp / 2), p)) % p; y = (pow(s, (s_exp + 1) >> 1, p) * pow(h, h_exp >> 1, p)) % p return y
Tonellis Algorithm
get_y_from_s
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/crypto/Easy_Crypto_Challenge/super_safe_encryption.py
MIT
def cookie_decode(session_cookie_value, secret_key=None): """ Decode a Flask cookie """ try: if(secret_key==None): compressed = False payload = session_cookie_value if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data else: app = MockApp(secret_key) si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.loads(session_cookie_value) except Exception as e: return "[Decoding error] {}".format(e) raise e
Decode a Flask cookie
cookie_decode
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/web/aMAZEing-challenge/cookie_decoder.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/web/aMAZEing-challenge/cookie_decoder.py
MIT
def sequence(index): """ Generate a W*****l number given the index """ element = (index << index) - 1 return element
Generate a W*****l number given the index
sequence
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/rev/lookup-rev/wpre.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/rev/lookup-rev/wpre.py
MIT
def is_prime(n): """ Check if a given number is prime """ return all(n % i for i in islice(count(2), int(sqrt(n)-1)))
Check if a given number is prime
is_prime
python
sajjadium/ctf-archives
ctfs/ImaginaryCTF/2021/rev/lookup-rev/wpre.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ImaginaryCTF/2021/rev/lookup-rev/wpre.py
MIT
def f(mat): """Make the key wavy""" N = 1600 T = 1/800 x = np.linspace(0, N*T, N) ys = [np.sum(np.array([.5**i * np.sin(n * 2 * np.pi * x) for i, n in enumerate(b)]), axis=0).tolist() for b in mat] return ys
Make the key wavy
f
python
sajjadium/ctf-archives
ctfs/HCMUS/2023/Quals/crypto/real_key/prob.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HCMUS/2023/Quals/crypto/real_key/prob.py
MIT
def save(): c_type=request.form['c_type'] print('ctype-(>'+c_type) if (c_type == 'php'): code=request.form['code'] if (len(code)<100): filename=get_random_string(6)+'.php' path='/home/app/test/'+filename f=open(path,'w') f.write(code) f.close() return filename else: return 'failed' """elif (c_type == 'python'): code=request.args.get('code') if (len(code)<30): filename=get_random_string(6)+'.py' path='/home/app/testpy/'+filename f=open(path,'w') f.write(code) f.close() return filename else: return 'failed'"""
elif (c_type == 'python'): code=request.args.get('code') if (len(code)<30): filename=get_random_string(6)+'.py' path='/home/app/testpy/'+filename f=open(path,'w') f.write(code) f.close() return filename else: return 'failed
save
python
sajjadium/ctf-archives
ctfs/3kCTF/2021/web/online_compiler/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/3kCTF/2021/web/online_compiler/app.py
MIT
def gen_pbox(s, n): """ Generate a balanced permutation box for an SPN :param s: Integer, number of bits per S-box. :param n: Integer, number of S-boxes. :return: List of integers, representing the generated P-box. """ return [(s * i + j) % (n * s) for j in range(s) for i in range(n)]
Generate a balanced permutation box for an SPN :param s: Integer, number of bits per S-box. :param n: Integer, number of S-boxes. :return: List of integers, representing the generated P-box.
gen_pbox
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def gen_sbox(n): """ Gen SBox for a given non negative integer n using a random permutation. Parameters: :param n: Integer, the bit size of sbox :return: List of integers, representing 2^n elements corresponding to the SBox permutation generated for the input. """ a, b = 2**((n + 1) // 2), 2**(n // 2) x = list(range(a)) random.shuffle(x) res = x[:] for i in range(b - 1): for j in range(len(x)): res.insert((i + 2) * j - 1, a * (i + 1) + x[j]) res = [res[i] for i in res] return res
Gen SBox for a given non negative integer n using a random permutation. Parameters: :param n: Integer, the bit size of sbox :return: List of integers, representing 2^n elements corresponding to the SBox permutation generated for the input.
gen_sbox
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def rotate_left(val, shift, mod): """ Rotate the bits of the value to the left by the shift amount. The function rotates the bits of the value to the left by the shift amount, wrapping the bits that overflow. The result is then masked by (1<<mod)-1 to only keep the mod number of least significant bits. :param val: Integer, the value to be rotated. :param shift: Integer, the number of places to shift the value to the left. :param mod: Integer, the modulo to be applied on the result. :return: Integer, the rotated value. """ shift = shift % mod return (val << shift | val >> (mod - shift)) & ((1 << mod) - 1)
Rotate the bits of the value to the left by the shift amount. The function rotates the bits of the value to the left by the shift amount, wrapping the bits that overflow. The result is then masked by (1<<mod)-1 to only keep the mod number of least significant bits. :param val: Integer, the value to be rotated. :param shift: Integer, the number of places to shift the value to the left. :param mod: Integer, the modulo to be applied on the result. :return: Integer, the rotated value.
rotate_left
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def __init__(self, SBOX, PBOX, key, rounds): """ Initialize the SPN class with the provided parameters. :param SBOX: List of integers representing the S-box. :param PBOX: List of integers representing the P-box. :param key: List of integers, bytes or bytearray representing the key. LSB BLOCK_SIZE bits will be used :param rounds: Integer, number of rounds for the SPN. """ self.SBOX = SBOX self.PBOX = PBOX self.SINV = [SBOX.index(i) for i in range(len(SBOX))] self.PINV = [PBOX.index(i) for i in range(len(PBOX))] self.BLOCK_SIZE = len(PBOX) self.BOX_SIZE = int(log2(len(SBOX))) self.NUM_SBOX = len(PBOX) // self.BOX_SIZE self.rounds = rounds self.round_keys = self.expand_key(key, rounds)
Initialize the SPN class with the provided parameters. :param SBOX: List of integers representing the S-box. :param PBOX: List of integers representing the P-box. :param key: List of integers, bytes or bytearray representing the key. LSB BLOCK_SIZE bits will be used :param rounds: Integer, number of rounds for the SPN.
__init__
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def perm(self, inp): """ Apply the P-box permutation on the input. :param inp: Integer, the input value to apply the P-box permutation on. :return: Integer, the permuted value after applying the P-box. """ ct = 0 for i, v in enumerate(self.PBOX): ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v) return ct
Apply the P-box permutation on the input. :param inp: Integer, the input value to apply the P-box permutation on. :return: Integer, the permuted value after applying the P-box.
perm
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def inv_perm(self, inp): """ Apply the inverse P-box permutation on the input. :param inp: Integer, the input value to apply the inverse P-box permutation on. :return: Integer, the permuted value after applying the inverse P-box. """ ct = 0 for i, v in enumerate(self.PINV): ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v) return ct
Apply the inverse P-box permutation on the input. :param inp: Integer, the input value to apply the inverse P-box permutation on. :return: Integer, the permuted value after applying the inverse P-box.
inv_perm
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def sbox(self, inp): """ Apply the S-box substitution on the input. :param inp: Integer, the input value to apply the S-box substitution on. :return: Integer, the substituted value after applying the S-box. """ ct, BS = 0, self.BOX_SIZE for i in range(self.NUM_SBOX): ct |= self.SBOX[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i) return ct
Apply the S-box substitution on the input. :param inp: Integer, the input value to apply the S-box substitution on. :return: Integer, the substituted value after applying the S-box.
sbox
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def inv_sbox(self, inp: int) -> int: """ Apply the inverse S-box substitution on the input. :param inp: Integer, the input value to apply the inverse S-box substitution on. :return: Integer, the substituted value after applying the inverse S-box. """ ct, BS = 0, self.BOX_SIZE for i in range(self.NUM_SBOX): ct |= self.SINV[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i) return ct
Apply the inverse S-box substitution on the input. :param inp: Integer, the input value to apply the inverse S-box substitution on. :return: Integer, the substituted value after applying the inverse S-box.
inv_sbox
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def int_to_list(self, inp): """ Convert a len(PBOX)-sized integer to a list of S-box sized integers. :param inp: Integer, representing a len(PBOX)-sized input. :return: List of integers, each representing an S-box sized input. """ BS = self.BOX_SIZE return [(inp >> (i * BS)) & ((1 << BS) - 1) for i in range(self.NUM_SBOX - 1, -1, -1)]
Convert a len(PBOX)-sized integer to a list of S-box sized integers. :param inp: Integer, representing a len(PBOX)-sized input. :return: List of integers, each representing an S-box sized input.
int_to_list
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def list_to_int(self, lst): """ Convert a list of S-box sized integers to a len(PBOX)-sized integer. :param lst: List of integers, each representing an S-box sized input. :return: Integer, representing the combined input as a len(PBOX)-sized integer. """ res = 0 for i, v in enumerate(lst[::-1]): res |= v << (i * self.BOX_SIZE) return res
Convert a list of S-box sized integers to a len(PBOX)-sized integer. :param lst: List of integers, each representing an S-box sized input. :return: Integer, representing the combined input as a len(PBOX)-sized integer.
list_to_int
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def expand_key(self, key, rounds): """ Derive round keys deterministically from the given key. :param key: List of integers, bytes, or bytearray representing the key. :param rounds: Integer, number of rounds for the SPN. :return: List of integers, representing the derived round keys. """ if isinstance(key, list): key = self.list_to_int(key) elif isinstance(key, (bytes, bytearray)): key = int.from_bytes(key, 'big') block_mask = (1 << self.BLOCK_SIZE) - 1 key = key & block_mask keys = [key] for _ in range(rounds): keys.append(self.sbox(rotate_left( keys[-1], self.BOX_SIZE + 1, self.BLOCK_SIZE))) return keys
Derive round keys deterministically from the given key. :param key: List of integers, bytes, or bytearray representing the key. :param rounds: Integer, number of rounds for the SPN. :return: List of integers, representing the derived round keys.
expand_key
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def encrypt(self, pt): """ Encrypt plaintext using the SPN, where the last round doesn't contain the permute operation. :param pt: Integer, plaintext input to be encrypted. :return: Integer, ciphertext after encryption. """ ct = pt ^ self.round_keys[0] for round_key in self.round_keys[1:-1]: ct = self.sbox(ct) ct = self.perm(ct) ct ^= round_key ct = self.sbox(ct) return ct ^ self.round_keys[-1]
Encrypt plaintext using the SPN, where the last round doesn't contain the permute operation. :param pt: Integer, plaintext input to be encrypted. :return: Integer, ciphertext after encryption.
encrypt
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def decrypt(self, ct): """ Decrypt ciphertext using the SPN, where the last round doesn't contain the permute operation. :param ct: Integer, ciphertext input to be decrypted. :return: Integer, plaintext after decryption. """ ct = ct ^ self.round_keys[-1] ct = self.inv_sbox(ct) for rk in self.round_keys[-2:0:-1]: ct ^= rk ct = self.inv_perm(ct) ct = self.inv_sbox(ct) return ct ^ self.round_keys[0]
Decrypt ciphertext using the SPN, where the last round doesn't contain the permute operation. :param ct: Integer, ciphertext input to be decrypted. :return: Integer, plaintext after decryption.
decrypt
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def encrypt_bytes(self, pt): """ Encrypt bytes using the SPN, in ECB on encrypt :param pt: bytes, should be multiple of BLOCK_SIZE//8 :return: bytes, ciphertext after block-by-block encryption """ block_len = self.BLOCK_SIZE // 8 assert len(pt) % block_len == 0 int_blocks = [int.from_bytes(pt[i:i + block_len], 'big') for i in range(0, len(pt), block_len)] return b''.join(self.encrypt(i).to_bytes(block_len, 'big') for i in int_blocks)
Encrypt bytes using the SPN, in ECB on encrypt :param pt: bytes, should be multiple of BLOCK_SIZE//8 :return: bytes, ciphertext after block-by-block encryption
encrypt_bytes
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
MIT
def istarmap(self, func, iterable, chunksize): ''' starmap equivalent using imap. Feel free to ignore this function for challenge purposes. ''' if self._state != mpp.RUN: raise ValueError("Pool not running") if chunksize < 1: raise ValueError("Chunksize must be 1+, not {0:n}".format(chunksize)) task_batches = mpp.Pool._get_tasks(func, iterable, chunksize) result = mpp.IMapIterator(self) self._taskqueue.put(( self._guarded_task_generation(result._job, mpp.starmapstar, task_batches), result._set_length )) return (item for chunk in result for item in chunk)
starmap equivalent using imap. Feel free to ignore this function for challenge purposes.
istarmap
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
MIT
def generate_graph(edges: List[List[int]]) -> nx.Graph: ''' Input: A list of edges (u, v) Output: A networkx graph ''' G = nx.Graph() for edge in edges: G.add_edge(*edge) return G
Input: A list of edges (u, v) Output: A networkx graph
generate_graph
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
MIT
def SymmetricEncrypt(key: bytes, plaintext: bytes) -> bytes: ''' Encrypt the plaintext using AES-CBC mode with provided key. Input: 16-byte key and plaintext Output: Ciphertext ''' if len(key) != 16: raise ValueError cipher = AES.new(key, AES.MODE_CBC) ct = cipher.encrypt(pad(plaintext, AES.block_size)) iv = cipher.iv return ct + iv
Encrypt the plaintext using AES-CBC mode with provided key. Input: 16-byte key and plaintext Output: Ciphertext
SymmetricEncrypt
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
MIT
def SymmetricDecrypt(key: bytes, ciphertext: bytes) -> bytes: ''' Decrypt the ciphertex using AES-CBC mode with provided key. Input: 16-byte key and ciphertext Output: Plaintext ''' if len(key) != 16: raise ValueError ct, iv = ciphertext[:-16], ciphertext[-16:] cipher = AES.new(key, AES.MODE_CBC, iv) pt = unpad(cipher.decrypt(ct), AES.block_size) return pt
Decrypt the ciphertex using AES-CBC mode with provided key. Input: 16-byte key and ciphertext Output: Plaintext
SymmetricDecrypt
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
MIT
def HashMAC(key: bytes, plaintext: bytes) -> bytes: ''' Input: Key and plaintext Output: A token on plaintext with the key using HMAC ''' token = HMAC.new(key, digestmod=SHA256) token.update(bytes(plaintext)) return token.digest()
Input: Key and plaintext Output: A token on plaintext with the key using HMAC
HashMAC
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
MIT
def keyGen(self, security_parameter: int) -> bytes: ''' Input: Security parameter Output: Secret key key_SKE||key_DES ''' key_SKE = get_random_bytes(security_parameter) key_DES = DES.keyGen(security_parameter) return key_SKE + key_DES
Input: Security parameter Output: Secret key key_SKE||key_DES
keyGen
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
MIT
def encryptGraph(self, key: bytes, G: nx.Graph) -> dict[bytes, bytes]: ''' Input: Secret key and a graph G Output: Encrypted graph encrypted_db ''' SPDX = computeSPDX(key, G, self.cores) key_DES = key[16:] EDB = DES.encryptDict(key_DES, SPDX, self.cores) del(SPDX) gc.collect() return EDB
Input: Secret key and a graph G Output: Encrypted graph encrypted_db
encryptGraph
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
MIT
def search(self, token: bytes, encrypted_db: dict[bytes, bytes]) -> Tuple(bytes, bytes): ''' Input: Search token Output: (tokens, cts) ''' resp, tok = b"", b"" curr = token while True: value = DES.search(curr, encrypted_db) if value == b'': break curr = value[:32] resp += value[32:] tok += curr return tuple([tok, resp])
Input: Search token Output: (tokens, cts)
search
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
MIT
def computeSDSP(G: nx.Graph, root): ''' Input: Graph G and a root Output: Tuples of the form ((start, root), (next_vertex, root)) ''' paths = nx.single_source_shortest_path(G, root) S = set() for _, path in paths.items(): path.reverse() if len(path) > 1: for i in range(len(path)-1): label = (path[i], root) value = (path[i+1],root) S.add((label, value)) return S
Input: Graph G and a root Output: Tuples of the form ((start, root), (next_vertex, root))
computeSDSP
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
MIT
def keyGen(self, security_parameter: int) -> bytes: ''' Input: Security parameter Output: Secret key ''' return get_random_bytes(security_parameter)
Input: Security parameter Output: Secret key
keyGen
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
MIT
def encryptDict(self, key: bytes, plaintext_dx: dict[bytes, bytes], cores: int) -> dict[bytes, bytes]: ''' Input: A key and a plaintext dictionary Output: An encrypted dictionary EDX ''' encrypted_db = {} chunk = int(len(plaintext_dx)/cores) iterable = product([key], plaintext_dx.items()) with Pool(cores) as pool: for ct_label, ct_value in pool.istarmap(encryptDictHelper, iterable, chunksize=chunk): encrypted_db[ct_label] = ct_value return encrypted_db
Input: A key and a plaintext dictionary Output: An encrypted dictionary EDX
encryptDict
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
MIT
def tokenGen(self, key: bytes, label: bytes) -> bytes: ''' Input: A key and a label Output: A token on label ''' K1 = utils.HashMAC(key, b'1'+label)[:16] K2 = utils.HashMAC(key, b'2'+label)[:16] return K1 + K2
Input: A key and a label Output: A token on label
tokenGen
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
MIT
def search(self, search_token: bytes, encrypted_db: dict[bytes, bytes]) -> bytes: ''' Input: Search token and EDX Output: The corresponding encrypted value. ''' K1 = search_token[:16] K2 = search_token[16:] hash_val = utils.Hash(K1) if hash_val in encrypted_db: ct_value = encrypted_db[hash_val] return utils.SymmetricDecrypt(K2, ct_value) else: return b''
Input: Search token and EDX Output: The corresponding encrypted value.
search
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
MIT
def init_table(): conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS blog_posts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, user_id TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ) """ ) conn.commit() conn.close()
CREATE TABLE IF NOT EXISTS blog_posts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, user_id TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) )
init_table
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/web/Chunky/blog/src/blog_posts/blog_posts.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/web/Chunky/blog/src/blog_posts/blog_posts.py
MIT
def init_table(): conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, username TEXT NOT NULL, password TEXT NOT NULL ) """ ) conn.commit() conn.close()
CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, username TEXT NOT NULL, password TEXT NOT NULL )
init_table
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/web/Chunky/blog/src/users/users.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/web/Chunky/blog/src/users/users.py
MIT
def whichmodule(obj, name): """Find the module an object belong to.""" module_name = getattr(obj, '__module__', None) if module_name is not None: return module_name # Protect the iteration by using a list copy of sys.modules against dynamic # modules that trigger imports of other modules upon calls to getattr. for module_name, module in sys.modules.copy().items(): if (module_name == '__main__' or module_name == '__mp_main__' # bpo-42406 or module is None): continue try: if _getattribute(module, name)[0] is obj: return module_name except AttributeError: pass return '__main__'
Find the module an object belong to.
whichmodule
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
MIT
def __init__(self, file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None): """This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, an io.BytesIO object, or any other custom object that meets this interface. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file-like object can be a binary file object opened for reading, a BytesIO object, or any other custom object that meets this interface. If *buffers* is not None, it should be an iterable of buffer-enabled objects that is consumed each time the pickle stream references an out-of-band buffer view. Such buffers have been given in order to the *buffer_callback* of a Pickler object. If *buffers* is None (the default), then the buffers are taken from the pickle stream, assuming they are serialized there. It is an error for *buffers* to be None if the pickle stream was produced with a non-None *buffer_callback*. Other optional arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects. """ self._buffers = iter(buffers) if buffers is not None else None self._file_readline = file.readline self._file_read = file.read self.memo = {} self.encoding = encoding self.errors = errors self.proto = 0 self.fix_imports = fix_imports
This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, an io.BytesIO object, or any other custom object that meets this interface. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file-like object can be a binary file object opened for reading, a BytesIO object, or any other custom object that meets this interface. If *buffers* is not None, it should be an iterable of buffer-enabled objects that is consumed each time the pickle stream references an out-of-band buffer view. Such buffers have been given in order to the *buffer_callback* of a Pickler object. If *buffers* is None (the default), then the buffers are taken from the pickle stream, assuming they are serialized there. It is an error for *buffers* to be None if the pickle stream was produced with a non-None *buffer_callback*. Other optional arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects.
__init__
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
MIT
def load(self): """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ # Check whether Unpickler was initialized correctly. This is # only needed to mimic the behavior of _pickle.Unpickler.dump(). if not hasattr(self, "_file_read"): raise UnpicklingError("Unpickler.__init__() was not called by " "%s.__init__()" % (self.__class__.__name__,)) self._unframer = _Unframer(self._file_read, self._file_readline) self.read = self._unframer.read self.readinto = self._unframer.readinto self.readline = self._unframer.readline self.metastack = [] self.stack = [] self.append = self.stack.append self.proto = 0 read = self.read dispatch = self.dispatch try: while True: key = read(1) if not key: raise EOFError assert isinstance(key, bytes_types) dispatch[key[0]](self) except _Stop as stopinst: return stopinst.value
Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file.
load
python
sajjadium/ctf-archives
ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
MIT
def gp(n) -> int: """ guess precision """ if str(n).endswith(".0"): return int(n) else: return float(n)
guess precision
gp
python
sajjadium/ctf-archives
ctfs/KalmarCTF/2023/web/HealthyCalc/chall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KalmarCTF/2023/web/HealthyCalc/chall.py
MIT
def signature(s): ''' generate a hmac signature for a given string ''' m = hmac.new(SECRET, digestmod=hashlib.sha256) m.update(s.encode('ascii')) return m.hexdigest()
generate a hmac signature for a given string
signature
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def get_db(): ''' helper function to get a sqlite database connection ''' db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) db.row_factory = sqlite3.Row return db
helper function to get a sqlite database connection
get_db
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def close_connection(exception): ''' helper function to close the database connection ''' db = getattr(g, '_database', None) if db is not None: db.close()
helper function to close the database connection
close_connection
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def query_db(query, args=(), one=False): ''' helper function to do a SQL query like select ''' cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv
helper function to do a SQL query like select
query_db
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def commit_db(query, args=()): ''' helper function to do SQl queries like insert into ''' get_db().cursor().execute(query, args) get_db().commit()
helper function to do SQl queries like insert into
commit_db
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def login_required(f): ''' login required decorator to ensure g.user exists ''' @wraps(f) def decorated_function(*args, **kwargs): if 'user' not in g or g.user == None: return redirect('/logout') return f(*args, **kwargs) return decorated_function
login required decorator to ensure g.user exists
login_required
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def before_request(): ''' session middleware. checks if we have a valid session and sets g.user ''' # request - flask.request if 'session' not in request.cookies: return None session = request.cookies['session'].split('.') if not len(session) == 2: return None key, sig = session if not hmac.compare_digest(sig, signature(key)): return None g.user= query_db('select * from users where uuid = ?', [key], one=True)
session middleware. checks if we have a valid session and sets g.user
before_request
python
sajjadium/ctf-archives
ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ALLES/2021/web/amazing-crypto-waf/app/app.py
MIT
def inc_bytes(a): """ Returns a new byte array with the value increment by 1 """ out = list(a) for i in reversed(range(len(out))): if out[i] == 0xFF: out[i] = 0 else: out[i] += 1 break return bytes(out)
Returns a new byte array with the value increment by 1
inc_bytes
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
MIT
def decrypt_block(self, ciphertext): """ Decrypts a single block of 16 byte long ciphertext. """ assert len(ciphertext) == 16 cipher_state = bytes2matrix(ciphertext) add_round_key(cipher_state, self._key_matrices[-1]) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) for i in range(self.n_rounds - 1, 0, -1): add_round_key(cipher_state, self._key_matrices[i]) inv_mix_columns(cipher_state) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) add_round_key(cipher_state, self._key_matrices[0]) return matrix2bytes(cipher_state)
Decrypts a single block of 16 byte long ciphertext.
decrypt_block
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
MIT
def render_emails(address): id = 0 render = """ <table> <tr> <th id="th-left">From</th> <th>Subject</th> <th id="th-right">Date</th> </tr> """ overlays = "" m = mails[address].copy() for email in m: render += f""" <tr id="{id}"> <td>{email['sender']}</td> <td>{email['subject']}</td> <td>{email['timestamp']}</td> </tr> """ overlays += f""" <div id="overlay-{id}" class="overlay"> <div class="email-details"> <h1>{email['subject']} - from: {email['sender']} to {email['rcpt']}</h1> <p>{email['body']}</p> </div> </div> """ id +=1 render += "</table>" render += overlays return render
overlays = "" m = mails[address].copy() for email in m: render += f
render_emails
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/web/Wanky_Mail/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/web/Wanky_Mail/app.py
MIT
def forward(self, x: Tensor) -> Tensor: """ Arguments: x: Tensor, shape ``[batch_size, seq_len, embedding_dim]`` """ x = x + self.pe[:, :x.size(1)] return x
Arguments: x: Tensor, shape ``[batch_size, seq_len, embedding_dim]``
forward
python
sajjadium/ctf-archives
ctfs/TSG/2023/rev/Natural_Flag_Processing_2/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSG/2023/rev/Natural_Flag_Processing_2/main.py
MIT
def decode(encoded_str): ''' Decode Base91 string to a bytearray ''' v = -1 b = 0 n = 0 out = bytearray() for strletter in encoded_str: if not strletter in decode_table: continue c = decode_table[strletter] if(v < 0): v = c else: v += c*91 b |= v << n n += 13 if (v & 8191)>88 else 14 while True: out += struct.pack('B', b&255) b >>= 8 n -= 8 if not n>7: break v = -1 if v+1: out += struct.pack('B', (b | v << n) & 255 ) return out
Decode Base91 string to a bytearray
decode
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
MIT
def encode(bindata): ''' Encode a bytearray to a Base91 string ''' b = 0 n = 0 out = '' for count in range(len(bindata)): byte = bindata[count:count+1] b |= struct.unpack('B', byte)[0] << n n += 8 if n>13: v = b & 8191 if v > 88: b >>= 13 n -= 13 else: v = b & 16383 b >>= 14 n -= 14 out += base91_alphabet[v % 91] + base91_alphabet[v // 91] if n: out += base91_alphabet[b % 91] if n>7 or b>90: out += base91_alphabet[b // 91] return out
Encode a bytearray to a Base91 string
encode
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
MIT
def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
Performs a call to reCaptcha API to validate the given response
verify
python
sajjadium/ctf-archives
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
MIT
def _chkpath(method, path): """Return an HTTP status for the given filesystem path.""" if method.lower() in ('put', 'delete'): return 501, "Not Implemented" # TODO elif method.lower() not in ('get', 'head'): return 405, "Method Not Allowed" elif os.path.isdir(path): return 400, "Path Not A File" elif not os.path.isfile(path): return 404, "File Not Found" elif not os.access(path, os.R_OK): return 403, "Access Denied" else: return 200, "OK"
Return an HTTP status for the given filesystem path.
_chkpath
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
MIT
def send(self, req, **kwargs): # pylint: disable=unused-argument """Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`? """ path = os.path.normcase(os.path.normpath(url2pathname(req.path_url))) response = requests.Response() response.status_code, response.reason = self._chkpath(req.method, path) if response.status_code == 200 and req.method.lower() != 'head': try: response.raw = open(path, 'rb') except (OSError, IOError) as err: response.status_code = 500 response.reason = str(err) if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url response.request = req response.connection = self return response
Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`?
send
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
MIT
def greeting(): bot = "" css = """ <br><br> <center> <strong><font size=5 color='purple'>Get New Year Quotes From Our New Year Bot!</font></strong> <br>_[<img src="https://i.imgur.com/uYBBhWn.gif" width="5%" />]_ </center> <style> .centered { position: fixed; /* or absolute */ top: 25%; left: 35%; } </style> """ front = """ <form action="/" method="POST" > <select name="type"> <option value="greeting_all">All</option> <option value="NewYearCommonList">Common</option> <option value="NewYearHealthList">Health</option> <option value="NewYearFamilyList">Family</option> <option value="NewYearWealthList">Wealth</option> </select> <input type="text" hidden name="number" value="%s" /> <input type="submit" value="Ask" /><br> </form> """%random.randint(0,3) greeting = "" try: debug = request.args.get("debug") if request.method == 'POST': greetType = request.form["type"] greetNumber = request.form["number"] if greetType == "greeting_all": greeting = random_greet(random.choice(NewYearCategoryList)) else: try: if greetType != None and greetNumber != None: greetNumber = re.sub(r'\s+', '', greetNumber) if greetType.isidentifier() == True and botValidator(greetNumber) == True: if len("%s[%s]" % (greetType, greetNumber)) > 20: greeting = fail else: greeting = eval("%s[%s]" % (greetType, greetNumber)) try: if greeting != fail and debug != None: greeting += "<br>You're choosing %s, it has %s quotes"%(greetType, len(eval(greetType))) except: pass else: greeting = fail else: greeting = random_greet(random.choice(NewYearCategoryList)) except: greeting = fail pass else: greeting = random_greet(random.choice(NewYearCategoryList)) if fail not in greeting: bot_list = ["( Β΄ βˆ€ `)γƒŽο½ž β™‘", "οΌˆβœΏβ—•α΄—β—•)γ€β”β”βœ«γƒ»*。", "(ΰΉ‘Λ˜α΅•Λ˜)"] else: bot_list = ["(β‰– οΈΏ β‰– ✿)", "α•™(⇀‸↼•)α•—", "(β‰– οΈΏ β‰– ✿)ꐦꐦ", "β”Œ( ΰ² _ΰ²  )β”˜"] bot = random.choice(bot_list) except: pass return "%s<div class='centered'>%s<strong><font color='red'>%s<br>NewYearBot >> </font></strong>%s</div>"%(css, front, bot, greeting)
front =
greeting
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/NewYearBot/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/NewYearBot/main.py
MIT
def get_shares_v2(password: str, n: int, t: int) -> Tuple[int, List[str]]: """ Get password shares. Args: password: the password to be shared. n: the number of non-master shares returned. t: the minimum number of non-master shares needed to recover the password. Returns: the shares, including the master share (n + 1 shares in total). """ assert n <= MASTER_SHARE_SZ master_share = randbits(MASTER_SHARE_SZ) unprocessed_non_master_shares = get_shares(password, n, t) non_master_shares = [] for i, share in enumerate(unprocessed_non_master_shares): v = CHAR_TO_INT[share[-1]] if (master_share >> i) & 1: v = (v + P // 2) % P non_master_shares.append(share[:-1] + INT_TO_CHAR[v]) return master_share, non_master_shares
Get password shares. Args: password: the password to be shared. n: the number of non-master shares returned. t: the minimum number of non-master shares needed to recover the password. Returns: the shares, including the master share (n + 1 shares in total).
get_shares_v2
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py
MIT
def get_shares(password: str, n: int, t: int) -> List[str]: """ Get password shares. Args: password: the password to be shared. n: the number of shares returned. t: the minimum number of shares needed to recover the password. Returns: the shares. """ assert len(password) <= t assert n > 0 ffes = [CHAR_TO_INT[c] for c in password] ffes += [randbelow(P) for _ in range(t - len(password))] result = [] for _ in range(n): coeffs = [randbelow(P) for _ in range(len(ffes))] s = sum([x * y for x, y in zip(coeffs, ffes)]) % P coeffs.append(s) result.append("".join(INT_TO_CHAR[i] for i in coeffs)) return result
Get password shares. Args: password: the password to be shared. n: the number of shares returned. t: the minimum number of shares needed to recover the password. Returns: the shares.
get_shares
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/shares/shares.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/shares/shares.py
MIT
def op(x1, x2): """Returns `(x1 + x2 + 2 * C * x1 * x2) / (1 - x1 * x2)`.""" if x2 == INFINITY: x1, x2 = x2, x1 if x1 == INFINITY: if x2 == INFINITY: return (-2 * C) % p elif x2 == 0: return INFINITY else: return -(1 + 2 * C * x2) * pow(x2, -1, p) % p if x1 * x2 == 1: return INFINITY return (x1 + x2 + 2 * C * x1 * x2) * pow(1 - x1 * x2, -1, p) % p
Returns `(x1 + x2 + 2 * C * x1 * x2) / (1 - x1 * x2)`.
op
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/algebra/algebra.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/algebra/algebra.py
MIT
def repeated_op(x, k): """Returns `x op x op ... op x` (`x` appears `k` times)""" s = 0 while k > 0: if k & 1: s = op(s, x) k = k >> 1 x = op(x, x) return s
Returns `x op x op ... op x` (`x` appears `k` times)
repeated_op
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/algebra/algebra.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/algebra/algebra.py
MIT
def merge_dicts(dict1, dict2) -> dict: """ Recursively merges dict2 into dict1 :param dict1: :param dict2: :return: """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for k in dict2: dict1[k] = merge_dicts(dict1[k], dict2[k]) if k in dict1 else dict2[k] return dict1
Recursively merges dict2 into dict1 :param dict1: :param dict2: :return:
merge_dicts
python
sajjadium/ctf-archives
ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
MIT
def load_config() -> dict: """ load conf based on environment :return: """ try: with open(current_dir + "config.yaml", "r", encoding="utf-8") as conf_main: conf = (yaml.safe_load(conf_main)) env = "dev" if os.environ.get("SCRIPT_ENV") == "production": env = "prod" elif os.environ.get("SCRIPT_ENV") == "staging": env = "staging" with open(current_dir + "config_%s.yaml" % env, "r", encoding="utf-8") as conf_f: conf = merge_dicts(conf, yaml.safe_load(conf_f)) return conf except FileNotFoundError: return {}
load conf based on environment :return:
load_config
python
sajjadium/ctf-archives
ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
MIT
def create_user(db: Session, user_create: UserCreate, ip_addr: str): """ username = Column(String, unique=True, nullable=False) password = Column(String, nullable=False) uploaded_model = Column(Boolean, nullable=False) registered_ip = Column(String, unique=True, nullable=False) """ db_user = User(username=user_create.username, password=hashlib.sha3_512(bytes(user_create.password, 'utf-8')).hexdigest(), uploaded_model=False, registered_ip=ip_addr, last_activity=datetime.now(), participated=0, ranking=0, register_date=datetime.now() ) db.add(db_user) db.commit()
username = Column(String, unique=True, nullable=False) password = Column(String, nullable=False) uploaded_model = Column(Boolean, nullable=False) registered_ip = Column(String, unique=True, nullable=False)
create_user
python
sajjadium/ctf-archives
ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py
MIT
def __init__(self,key,rounds=32): """Create a PRESENT cipher object key: the key as a 128-bit or 80-bit rawstring rounds: the number of rounds as an integer, 32 by default """ self.rounds = rounds if len(key) * 8 == 80: self.roundkeys = generateRoundkeys80(byte2number(key),self.rounds) elif len(key) * 8 == 128: self.roundkeys = generateRoundkeys128(byte2number(key),self.rounds) else: raise (ValueError, "Key must be a 128-bit or 80-bit rawstring")
Create a PRESENT cipher object key: the key as a 128-bit or 80-bit rawstring rounds: the number of rounds as an integer, 32 by default
__init__
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def encrypt(self,block): """Encrypt 1 block (8 bytes) Input: plaintext block as raw string Output: ciphertext block as raw string """ state = byte2number(block) for i in range(self.rounds-1): state = addRoundKey(state,self.roundkeys[i]) state = sBoxLayer(state) state = pLayer(state) cipher = addRoundKey(state,self.roundkeys[-1]) return number2byte_N(cipher,8)
Encrypt 1 block (8 bytes) Input: plaintext block as raw string Output: ciphertext block as raw string
encrypt
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def decrypt(self,block): """Decrypt 1 block (8 bytes) Input: ciphertext block as raw string Output: plaintext block as raw string """ state = byte2number(block) for i in range(self.rounds-1): state = addRoundKey(state,self.roundkeys[-i-1]) state = pLayer_dec(state) state = sBoxLayer_dec(state) decipher = addRoundKey(state,self.roundkeys[0]) return number2byte_N(decipher,8)
Decrypt 1 block (8 bytes) Input: ciphertext block as raw string Output: plaintext block as raw string
decrypt
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def generateRoundkeys80(key,rounds): """Generate the roundkeys for a 80-bit key Input: key: the key as a 80-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers""" roundkeys = [] for i in range(1,rounds+1): # (K1 ... K32) # rawkey: used in comments to show what happens at bitlevel # rawKey[0:64] roundkeys.append(key >>16) #1. Shift #rawKey[19:len(rawKey)]+rawKey[0:19] key = ((key & (2**19-1)) << 61) + (key >> 19) #2. SBox #rawKey[76:80] = S(rawKey[76:80]) key = (Sbox[key >> 76] << 76)+(key & (2**76-1)) #3. Salt #rawKey[15:20] ^ i key ^= i << 15 return roundkeys
Generate the roundkeys for a 80-bit key Input: key: the key as a 80-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers
generateRoundkeys80
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def generateRoundkeys128(key,rounds): """Generate the roundkeys for a 128-bit key Input: key: the key as a 128-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers""" roundkeys = [] for i in range(1,rounds+1): # (K1 ... K32) # rawkey: used in comments to show what happens at bitlevel roundkeys.append(key >>64) #1. Shift key = ((key & (2**67-1)) << 61) + (key >> 67) #2. SBox key = (Sbox[key >> 124] << 124)+(Sbox[(key >> 120) & 0xF] << 120)+(key & (2**120-1)) #3. Salt #rawKey[62:67] ^ i key ^= i << 62 return roundkeys
Generate the roundkeys for a 128-bit key Input: key: the key as a 128-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers
generateRoundkeys128
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def sBoxLayer(state): """SBox function for encryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(16): output += Sbox[( state >> (i*4)) & 0xF] << (i*4) return output
SBox function for encryption Input: 64-bit integer Output: 64-bit integer
sBoxLayer
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def sBoxLayer_dec(state): """Inverse SBox function for decryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(16): output += Sbox_inv[( state >> (i*4)) & 0xF] << (i*4) return output
Inverse SBox function for decryption Input: 64-bit integer Output: 64-bit integer
sBoxLayer_dec
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def pLayer(state): """Permutation layer for encryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(64): output += ((state >> i) & 0x01) << PBox[i] return output
Permutation layer for encryption Input: 64-bit integer Output: 64-bit integer
pLayer
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def pLayer_dec(state): """Permutation layer for decryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(64): output += ((state >> i) & 0x01) << PBox_inv[i] return output
Permutation layer for decryption Input: 64-bit integer Output: 64-bit integer
pLayer_dec
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def byte2number(i): """ Convert a string to a number Input: byte (big-endian) Output: long or integer """ return int.from_bytes(i, 'big')
Convert a string to a number Input: byte (big-endian) Output: long or integer
byte2number
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def number2byte_N(i, N): """Convert a number to a string of fixed size i: long or integer N: length of byte Output: string (big-endian) """ return i.to_bytes(N, byteorder='big')
Convert a number to a string of fixed size i: long or integer N: length of byte Output: string (big-endian)
number2byte_N
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def get_common_logger(name: str, log_level: str = "DEBUG", log_file_path: str = None, std_out: bool = True, backup_count: int = 180): """ :param name: :param log_level: :param log_file_path: :param std_out: :param backup_count: :return: """ logger = getLogger(name) if log_level == "WARN": log_level = WARN elif log_level == "INFO": log_level = INFO else: log_level = DEBUG formatter = Formatter("%(asctime)s %(levelname)s %(module)s %(lineno)s :%(message)s") if log_file_path is not None: os.makedirs(os.path.dirname(log_file_path), exist_ok=True) handler = TimedRotatingFileHandler(filename=log_file_path, when="midnight", backupCount=backup_count, encoding="utf-8", delay=True) handler.setLevel(log_level) handler.setFormatter(formatter) logger.addHandler(handler) if std_out: handler = StreamHandler(sys.stdout) handler.setLevel(log_level) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(log_level) logger.propagate = False return logger
:param name: :param log_level: :param log_file_path: :param std_out: :param backup_count: :return:
get_common_logger
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
MIT
def set_logger(name: str, log_conf: dict, backup_count: int = 180): """ set the logger for different usage :param name: :param log_conf: :param backup_count: :return: """ return get_common_logger(name, log_level=log_conf["level"], log_file_path=os.path.dirname(__file__) + "/../.." + log_conf["log_file_path"], std_out=log_conf["std_out"], backup_count=backup_count)
set the logger for different usage :param name: :param log_conf: :param backup_count: :return:
set_logger
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
MIT
def visit(baseUrl: str, link: str) -> str: """Visit the website""" p = multiprocessing.Process(target=_visit, args=(baseUrl, link)) p.start() return f"Visiting {link}"
Visit the website
visit
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
MIT
def route_traffic() -> Response: """Route the traffic to upstream""" microservice = request.args.get("service", "home_page") route = routes.get(microservice, None) if route is None: return abort(404) # Fetch the required page with arguments appended raw_query_param = request.query_string.decode() print(f"Requesting {route} with q_str {raw_query_param}", file=sys.stderr) res = get(f"{route}/?{raw_query_param}") headers = [ (k, v) for k, v in res.raw.headers.items() if k.lower() not in excluded_headers ] return Response(res.content, res.status_code, headers)
Route the traffic to upstream
route_traffic
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
MIT
def not_found(e) -> Response: """404 error""" return Response(f"""Error 404: This page is not found: {e}""", 404)
404 error
not_found
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
MIT
async def index(request: Request): """ The base service for admin site """ # Currently Work in Progress requested_service = request.query_params.get("service", None) if requested_service is None: return {"message": "requested service is not found"} # Filter external parties who are not local if requested_service == "admin_page": return {"message": "admin page is currently not a requested service"} # Legit admin on localhost requested_url = request.query_params.get("url", None) if requested_url is None: return {"message": "URL is not found"} # Testing the URL with admin response = get(requested_url, cookies={"cookie": admin_cookie}) return Response(response.content, response.status_code)
The base service for admin site
index
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
MIT
def homepage() -> Response: """The homepage for the app""" cookie = request.cookies.get("cookie", "Guest Pleb") # If admin, give flag if cookie == admin_cookie: return render_template("flag.html", flag=FLAG, user="admin") # Otherwise, render normal page response = make_response(render_template("index.html", user=cookie)) response.set_cookie("cookie", cookie) return response
The homepage for the app
homepage
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
MIT
def is_sus(microservice: str, cookies: dict) -> bool: """Check if the arguments are sus""" acc = [val for val in cookies.values()] acc.append(microservice) for word in acc: for char in word: if char in banned_chars: return True return False
Check if the arguments are sus
is_sus
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
MIT