Challenge example

Code source example

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os


KEY = os.urandom(16)
FLAG = "FLAG{FakeFLAG}"

def encrypt(plaintext):
    padded = pad(plaintext + FLAG.encode(), 16)
    cipher = AES.new(KEY, AES.MODE_ECB)
    try:
        encrypted = cipher.encrypt(padded)
    except ValueError as e:
        return {"error": str(e)}

    return {"ciphertext": encrypted.hex()}


data = input("Data to encrypt : ")
data = bytes.fromhex(data)

cipher = encrypt(data)
print(cipher)

The objective of this challenge is to retrieve the FLAG which is encrypted with the user input.

The challenge is served using socat so the user can only send data and receive the ciphertext.

Exploitation

Here an oracle is possible as the user can inject and manipulate arbitrary data into the targeted ciphertext as he want and he have the ciphertext output.

By sending 32 bytes, the user can prooved that ECB mode is used :

from pwn import *
import json

p = remote("127.0.0.1", 1337)
p.recvuntil(b": ")

p.sendline((b"A"*32).hex().encode())

ciphertext = json.loads(p.recvline())['ciphertext']

assert(ciphertext[0:32] == ciphertext[32:64])
print("remote service use ECB mode")

output :

$ python3 exploit.py
[+] Opening connection to 127.0.0.1 on port 1337: Done
remote service use ECB mode
[*] Closed connection to 127.0.0.1 port 1337

As ECB is used, it's possible to bruteforce the FLAG :

from pwn import *
import json
from rich.console import Console
import string

printable = [ord(c) for c in string.printable]

console = Console()
context.log_level = 'error'

def encrypt(payload):
    p = remote("127.0.0.1", 1337)
    p.recvuntil(b": ")

    p.sendline(payload.hex().encode())

    data = json.loads(p.recvline())['ciphertext']

    p.close()
    return data


flag = b""
with console.status(f"FLAG = {flag}, Trying byte : ") as a:
    while len(flag) == 0 or flag[-1] != 125:
        for c in printable:
            # set char to test
            c = c.to_bytes(1,'big')
            # update the console status
            a.update(f"FLAG = {flag}, Trying byte : {c}")
            # Set the payload
            if len(flag) > 16:
                payload = flag[-15:] + c + b'\x10' * (15 - (len(flag) % 16))
            else:
                payload = b'\x10' * (15 - len(flag)) + flag + c + b'\x10' * (15 - len(flag))
            cipher = encrypt(payload)
            
            # Check if the first block and the targeted block are the same
            if cipher[0:32] == cipher[32 + (32 * (len(flag) // 16)) : 64 + (32 * (len(flag) // 16 ))]:
                # If it is, then the letter is found
                flag += c
                break

print("FLAG = ", flag)

Note: not all bytes are tester, only printable characters are tested as the flag must be human readable.

Last updated