Lab 9: (Extra) RSA & Hashing

RSA

Weโ€™ll be doing the first 2 RSA challenges from the asymmetric cryptography section.

In the first challenge, the run script will generate the public and private keys for you using PyCryptoDome, encipher the flag using the generated public key, and print it in hex string format.

You will use the generated private key to decrypt the flag.

The source for the first challenge script is shown below:

#!/usr/bin/exec-suid -- /usr/bin/python3 -I

from Crypto.PublicKey import RSA

flag = open("/flag", "rb").read()
assert len(flag) <= 256

key = RSA.generate(2048)
print(f"(public)  n = {key.n:#x}")
print(f"(public)  e = {key.e:#x}")
print(f"(private) d = {key.d:#x}")

ciphertext = pow(
    int.from_bytes(flag, "little"),
    key.e, key.n,
).to_bytes(256, "little")
print(f"Flag Ciphertext (hex): {ciphertext.hex()}")

In the second challenge, the run script will again encrypt the flag using a generated public key. This time, the script will give you the values of ๐‘›, ๐‘, and ๐‘ž, and you will need to do a little more work to recover the private key and decrypt the flag.

The source for the second challenge script is below:

#!/usr/bin/exec-suid -- /usr/bin/python3 -I

from Crypto.PublicKey import RSA

flag = open("/flag", "rb").read()
assert len(flag) <= 256

key = RSA.generate(2048)
print(f"e = {key.e:#x}")
print(f"p = {key.p:#x}")
print(f"q = {key.q:#x}")

ciphertext = pow(
    int.from_bytes(flag, "little"),
    key.e, key.n,
).to_bytes(256, "little")
print(f"Flag Ciphertext (hex): {ciphertext.hex()}")

RSA Signatures

This challenge is an RSA forgery problem presented in a worker/dispatcher format.

Here, the /challenge/dispatcher script is your โ€œoracleโ€ that will sign any message (given as a command line argument) except the command โ€œflagโ€.

It takes its input as a base64-encoded string, which it will decode into the actual message to be signed. It will then sign the message using a pre-generated private key, encode the signature in base64, and print the result.

The dispatcher script is as follows:

#!/usr/bin/exec-suid -- /usr/bin/python3 -I

import sys

from base64 import b64encode, b64decode

n = int(open("/challenge/key-n").read(), 16)
d = int(open("/challenge/key-d").read(), 16)

if len(sys.argv) < 2:
    print(f"Usage: {sys.argv[0]} [command-b64]")
    sys.exit(1)

command = b64decode(sys.argv[1].strip("\0"))

if b"flag" in command:
    print(f"Command contains 'flag'")
    sys.exit(1)

signature = pow(
    int.from_bytes(command, "little"), d, n
).to_bytes(256, "little")
print(f"Signed command (b64): {b64encode(signature).decode()}")

The base64-encoded, signed command can then be passed as a command line argument to the /challenge/worker script, which decode the signature, then decrypt it using the public key to obtain the original message. Thus, the worker should only accept commands that have been signed by the dispatcher.

If this message was โ€œflagโ€, it will print the flag, otherwise it will do nothing.

Note that the original message is not passed to the worker in addition to the signature.

The worker script is as follows:

#!/usr/bin/exec-suid -- /usr/bin/python3 -I

import sys

from base64 import b64decode

n = int(open("/challenge/key-n").read(), 16)
e = int(open("/challenge/key-e").read(), 16)

if len(sys.argv) < 2:
    print(f"Usage: {sys.argv[0]} [signature-b64]")
    sys.exit(1)

signature = b64decode(sys.argv[1])
c = int.from_bytes(signature, "little")
assert c < n, "Message too big!"
command = pow(c, e, n).to_bytes(256, "little").rstrip(b"\x00")

print(f"Received signed command: {command}")
if command == b"flag":
    print(open("/flag").read())

SHA 1

This challenge requires you to find a partial hash collision with the flag under SHA256.

The run script is as follows:

#!/usr/bin/exec-suid -- /usr/bin/python3 -I

import hashlib

flag = open("/flag").read()
prefix_length = 6
flag_hash = hashlib.sha256(flag.encode("latin")).hexdigest()
print(f"{flag_hash[:prefix_length]=}")

collision = bytes.fromhex(input("Colliding input? ").strip())
collision_hash = hashlib.sha256(collision).hexdigest()
print(f"{collision_hash[:prefix_length]=}")
if collision_hash[:prefix_length] == flag_hash[:prefix_length]:
    print("Collided!")
    print(flag)

Python Multiprocessing Example

Note: this may not work on your local machine because Pythonโ€™s multiprocessing module is notoriously finicky. If you would like to test multiprocessing locally, use the multiprocess external library, which is a drop-in replacement that solves a lot of issues.

from multiprocessing.pool import Pool

# define a worker function to be run in each process
# it will take a starting value, and count all of the 
# numbers divisible by 7 in the specified range.
# 
# as a rule of thumb, you'll want your workers doing a significant
# amount of CPU-bound work, since there is a cost associated with
# initializing processes.
# hence our choice of job size 1 million.
def worker(init: int):
    start, end = init * 1000000, (init + 1) * 1000000
    print(f"counting from {start} to {end}")
    count = 0
    for i in range(start, end):
        if i % 7 == 0:
            count += 1
    return count

# number of processes should be <= number of available cpus
# because there isn't really any point in creating more if they'll
# just be suspended anyways.
with Pool(processes=10) as pool:
    # pool.map will assign the values of the second, iterable parameter
    # to the first parameter, a function that takes a single argument.
    # the return values are stored in a list sorted in the same order
    # as the arguments given.
    results = pool.map(worker, range(10))

print(f"# of #'s divisible by 7 below 10 million: {sum(results)}")

Post-Lab

There is no postlab for this lab.