Only true hackers can see the image in this magic PNG….
nc crypto.chal.csaw.io 8000
Author: Sophia D’Antoine
We are given with python script, Netcat command and a hint about a PNG file. Let’s run Netcat and see what we will get:
[Megabeets] /tmp/CSAW/clam# nc crypto.chal.csaw.io 8000
<alot of base64 text here>
We received a base64 encoded text from the server. It is probably our image so let’s decode it and save it to file:
[Megabeets]$> nc crypto.chal.csaw.io 8000 | base64 --decode > out.png
Trying to open the image we faced with an error, our image-viewer could not open the file. Open the file with text viewer and see that there is no PNG header. So, we have the image but it somehow encoded and we need to find out how to decode it. Let’s look at the script, the answer will probably be there. It’s not so long so I attached it here:
from twisted.internet import reactor, protocol
PORT = 9013
return open(filename, "rb").read()
KEY = "[CENSORED]"
image = get_bytes_from_file("./sleeping.png")
encoded_string = base64.b64encode(image)
key_len = length_encryption_key()
print 'Sending magic....'
if key_len != 12:
resp = get_magic_png()
protocol = MyServer
factory = MyServerFactory()
Look at the highlighted rows. You can see that after encoding the file with base64 the script is checking whether the size of the encryption key is 12 . We don’t see any encryption in the script except the encoding itself but we can assume that in the original script an encryption is done using 12 bytes long key. But what encryption? There are billion of options, how can we find the right decryption algorithm to use? Well, the answer is simple – this is a CTF and the admins know that we cannot try all the possible decryption methods so it will probably be the banal option: XOR.
After choosing our encryption method let’s think how can we find the key itself. We know the file is a PNG image, so we can XOR the first 12 bytes of the encrypted flle with the first 12 bytes of normal PNG file.
89 50 4E 47 0D 0A 1A 0A 00 00 00 0D XOR DE 3F 0F 2F 52 4B 45 41 65 79 21 32 == 57 6F 41 68 5F 41 5F 4B 65 79 21 3F
which in ASCII is: “WoAh_A_Key!?”
Now that we have the key we can let python do it’s magic:
def xor(data, key):
l = len(key)
(data[i] ^ key[i % l]) for i in range(0,len(data))
# Read the encrypted image as bytearray
data = bytearray(open('out.png', 'rb').read())
# This is our key as bytearray: "WoAh_A_Key!?"
key = bytearray([0x57, 0x6f, 0x41, 0x68, 0x5f, 0x41, 0x5f, 0x4b, 0x65, 0x79, 0x21, 0x3f])
with open('decrypted.png', 'w') as file_:
And you’ll get the image and the flag: