August 13, 2017

SHA2017 writeups: Crypto : Stack Overflow (100)

Last weekend I participated in the SHA2017 CTF https://ctf.sha2017.org/with my team HackingForSoju. We ended up at third place. Here are the writeups for the levels I solved.

Crypto : Stack Overflow (100)

I had some issues implementing strong encryption, luckily I was able to find a nice example on stackoverflow that showed me how to do it.
The attached archive contained two files, encrypt.py and flag.pdf.enc.

encrypt.py:

import os, sys
from Crypto.Cipher import AES

fn = sys.argv[1]
data = open(fn,'rb').read()

# Secure CTR mode encryption using random key and random IV, taken from
# http://stackoverflow.com/questions/3154998/pycrypto-problem-using-aesctr
secret = os.urandom(16)
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret)

encrypted = crypto.encrypt(data)
open(fn+'.enc','wb').write(encrypted)


This is not a good implementation, as every 16-bit block will be XOR-ed with the same key. It is enough to just know 16 bytes of plaintext to extract the key. The name of the encrypted file suggests that it in a PDF, wich has a predictable file header.

Here is the script I wrote to solve break the key:

# Input data as integers
data = map(ord, open('flag.pdf.enc').read())

# Plaintext, as integers
plain = map(ord, '%PDF-1.3 \n1 0 ob')

# Key is plaintext XOR:ed with ciphertext
key = [a^b for a,b in zip(plain[:16],data)]

# Decrypt and save
msg = [chr(a^b) for a,b in zip(key*len(data), data)]
f = open('flag.pdf','w')
f.write(''.join(msg))
f.close()

The contents of the decrypted file is an image with the flag and an important message:



No comments:

Post a Comment