🏳️
The CTF Recipes
  • Introduction
  • Cryptography
    • Introduction
    • General knowledge
      • Encoding
        • Character encoding
          • ASCII
          • Unicode
          • UTF-8
        • Data encoding
          • Base16
          • Base32
          • Base64
      • Maths
        • Modular arithmetic
          • Greatest Common Divisor
          • Fermat's little theorem
          • Quadratic residues
          • Tonelli-Shanks
          • Chinese Remainder Theorem
          • Modular binomial
      • Padding
        • PKCS#7
    • Misc
      • XOR
    • Mono-alphabetic substitution
      • Index of coincidence
      • frequency analysis
      • Well known algorithms
        • 🔴Scytale
        • 🔴ROT
        • 🔴Polybe
        • 🔴Vigenere
        • 🔴Pigpen cipher
        • 🔴Affine cipher
    • Symmetric Cryptography
      • AES
        • Block Encryption procedure
          • Byte Substitution
          • Shift Row
          • Mix Column
          • Add Key
          • Key Expansion / Key Schedule
        • Mode of Operation
          • ECB
            • Block shuffling
              • Challenge example
            • ECB Oracle
              • Challenge example
          • CBC
            • Bit flipping
              • Challenge example
            • Padding oracle
              • Challenge example
          • OFB
            • Key stream reconstruction
            • Encrypt to Uncrypt
  • 🛠️Pwn
    • General knowledge
      • STACK
        • Variables storage
        • Stack frame
      • PLT and GOT
      • HEAP
        • HEAP operations
        • Chunk
        • Bins
        • Chunk allocation and reallocation
      • Syscall
    • Architectures
      • aarch32
        • Registers
        • Instruction set
        • Calling convention
      • aarch64
        • Registers
        • Instruction set
        • Calling convention
      • mips32
        • Registers
        • Instruction set
        • Calling convention
      • mips64
        • Registers
        • Instruction set
        • Calling convention
      • x86 / x64
        • Registers
        • Instruction set
        • Calling convention
    • Stack exploitation
      • Stack Buffer Overflow
        • Dangerous functions
          • gets
          • memcpy
          • sprintf
          • strcat
          • strcpy
        • Basics
          • Challenge example
        • Instruction pointer Overwrite
          • Challenge example
        • De Bruijn Sequences
        • Stack reading
          • Challenge example
      • Format string
        • Dangerous functions
          • printf
          • fprintf
        • Placeholder
        • Data Leak
          • Challenge example
        • Data modification
          • Challenge example
      • Arbitrary code execution
        • Shellcode
        • ret2reg
        • Code reuse attack
          • Ret2plt
          • Ret2dlresolve
          • GOT Overwrite
          • Ret2LibC
          • Leaking LibC
          • Ret2csu
          • Return Oriented Programming - ROP
          • Sigreturn Oriented Programming - SROP
          • Blind Return Oriented Programming - BROP
            • Challenge example
          • 🔴Call Oriented Programming - COP
          • 🔴Jump Oriented Programming - JOP
          • One gadget
        • Stack pivoting
    • 🛠️Heap exploitation
      • Heap overflow
        • Challenge example
      • Use after free
        • Challenge example
      • 🛠️Double free
      • 🔴Unlink exploit
    • Protections
      • Stack Canaries
      • No eXecute
      • PIE
      • ASLR
      • RELRO
    • Integer overflow
Powered by GitBook
On this page
  • Code source example
  • Exploitation
  1. Cryptography
  2. Symmetric Cryptography
  3. AES
  4. Mode of Operation
  5. ECB
  6. ECB Oracle

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.

PreviousECB OracleNextCBC

Last updated 2 years ago