Google CTF 2018 shall we play a game

Although we haven’t managed to submit the flag correctly, I’m still publishing this write-up. Maybe it helps someone.

The Google CTF 2018 “shall we play a game?” challenge:

This was in the reverse engineering category, only included a link to an apk file (mirror) and the short description to win the game 1’000’000 times to get the flag.

I already had the setup to run and investigate Android Apps from a very great BSides Munich workshop Fun with Frida. In the end I didn’t end up using Frida to solve the challenge, but the setup alone helped a lot already.

Looking at the game, it is a very simple tic-tac-toe game with a win counter that goes up to 1’000’000:

Starting to reverse it I’ve used unpack-apk.sh to extract the apk file and attempt to decompile it as well. Looking at the source code at app/extracted/src/main/java/com/google/ctf/shallweplayagame/GameActivity.java we find that this is the main program. Two functions there are of interest to us (comments by me):

    // Display flag and some magic we don't understand
    void m() {
        Object _ = N._(Integer.valueOf(0), N.a, Integer.valueOf(0));
        Object _2 = N._(Integer.valueOf(1), N.b, this.q, Integer.valueOf(1));
        N._(Integer.valueOf(0), N.c, _, Integer.valueOf(2), _2);
        ((TextView) findViewById(R.id.score)).setText(new String((byte[]) N._(Integer.valueOf(0), N.d, _, this.r)));
        o();
    }

    void n() {
        // Reset the board, remove X and O from the board
        for (int i = 0; i < 3; i++) {
            for (int i2 = 0; i2 < 3; i2++) {
                this.l[i2][i].a(a.EMPTY, 25);
            }
        }
        k();
        // Increase win counter
        this.o++;
        // Some magic we don't understand
        Object _ = N._(Integer.valueOf(2), N.e, Integer.valueOf(2));
        N._(Integer.valueOf(2), N.f, _, this.q);
        this.q = (byte[]) N._(Integer.valueOf(2), N.g, _);
        // Check if win counter is 1'000'000
        if (this.o == 1000000) {
            // Show the flag
            m();
            return;
        }
        ((TextView) findViewById(R.id.score)).setText(String.format("%d / %d", new Object[]{Integer.valueOf(this.o), Integer.valueOf(1000000)}));
    }

My first attempts were to start the game with a win counter of already 999’999 or decrease the 1’000’000 to 2. But neither worked, we won the game but instead of the flag we’d get binary garbage displayed. It’s clear that the magic we don’t understand needs to run 1’000’000 to produce the correct string (line 21 – 23).

I’ve started to look at the assembly file app/extracted/smali/com/google/ctf/shallweplayagame/GameActivity.smali and the method n() as that’s where we need to make changes:


.method n()V
    .locals 10

    const v9, 0xf4240

This must be the right place, 0xf4240 is 1’000’000 in hex. We can somewhat easy find the increase of the win counter:


    iget v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I

    add-int/lit8 v0, v0, 0x1

    iput v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I

And further down is the win check:


    iget v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I

    if-ne v0, v9, :cond_2

    invoke-virtual {p0}, Lcom/google/ctf/shallweplayagame/GameActivity;->m()V

Between those sections, we need to add a new loop which runs 1’000’000 times. I’ve did that with the following patch:


--- orig/GameActivity.smali	2018-06-26 10:47:29.072510136 +0200
+++ patched/GameActivity.smali	2018-06-26 11:21:00.495157390 +0200
@@ -664,7 +664,8 @@
 .end method
 
 .method n()V
-    .locals 10
+    # Increase local variable count by one
+    .locals 11
 
     const v9, 0xf4240
 
@@ -676,6 +677,9 @@
 
     const/4 v6, 0x2
 
+    # Add new variable v10 with value 0
+    const v10, 0x0
+
     move v2, v1
 
     :goto_0
@@ -716,8 +720,20 @@
 
     add-int/lit8 v0, v0, 0x1
 
+    # move 1'000'000 into the win counter, we now only need to win once
+    move v0, v9
+
     iput v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I
 
+    # add new loop, goto_3 label
+    :goto_3
+
+    # break out condition, if v10 is 1'000'000 goto cond_3
+    if-ge v10, v9, :cond_3
+
+    # increase loop counter v10 by 1
+    add-int/lit8 v10, v10, 0x1
+
     new-array v0, v7, [Ljava/lang/Object;
 
     invoke-static {v6}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
@@ -786,6 +802,12 @@
 
     iput-object v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->q:[B
 
+    # end of the for loop, jump back up to goto_3 label until v10 is 1'000'000
+    goto :goto_3
+
+    # break out label, jump here if v10 is 1'000'000
+    :cond_3
+
     iget v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I
 
     if-ne v0, v9, :cond_2

Now we just need to build a new apk file, zipalign it, sign it, install it on our emulator and run it:


# apktool b
# zipalign -v 4 dist/app.apk app.aligned.apk
# jarsigner -verbose -storepass android -keystore ~/.android/debug.keystore app.aligned.apk signkey
# adb install app.aligned.apk

And when we run it finally this screen is displayed:

The flag is CTF{ThLssOfInncncIsThPrcOfAppls} or CTF{ThLssOfInncncIsThPrcOfAppIs} or CTF{ThLssOflnncncIsThPrcOfAppls} – I’m still not sure.

XSS on forge.puppet.com

I found a vulnerability on forge.puppet.com which allowed me to store XSS on their module page for a module I own.
User interaction was still required to execute the JavaScript payload by hovering over a link on the page, thus the risk was rather limited.

The issue was that not all values in metadata.json of uploaded modules were correctly sanitized. You could upload a module with the following metadata.json payload (abbreviated):

  "operatingsystem_support": [
    {
      "operatingsystem":"CentOS",
      "operatingsystemrelease":[ "5", "6", "7<script>alert('xss')</script>" ]
    }
  ],

When a user then visited the module page and hovered over the “CentOS” link, to figure out which versions are supported, then the JavaScript payload would be executed:

This issue has been fixed by the Puppet team.

Timeline:
2018-03-24 – Issue was reported to the Puppet security team.
2018-04-01 – Asking for feedback if the report has been received.
2018-04-01 – Puppet security team confirms and says it’s added to their backlog.
2018-06-13 – Asking for feedback if the issue is resolved.
2018-06-13 – Puppet security team confirms it’s fixed, possibly already since March.

 

WPICTF 2018 guess5

The WPICTF 2018 “guess5” challenge:

The URL presented us with a guessing game, we have to pick 6 numbers. If we picked the correct numbers we’ll get a flag:

However submitting our picks never worked. Investigating this for a bit it looks like this requires to run a local Ethereum node. Before trying to set that up we’ve looked more into what the web application does. Interestingly it fetches the URL https://glgaines.github.io/guess5/Guess6.json (mirror here). In there we can find the ETH contract including in plain text for some reason. Which contains the flag:

The flag is: WPI{All_Hail_The_Mighty_Vitalik}

WPICTF 2018 Shell-JAIL-2

The WPICTF 2018 “Shell-JAIL-2” challenge:

This is almost the same challenge as Shell-JAIL-1 (see my write-up here for explanation of details) with the exception of one extra line in access.c (full mirror here):

        setenv("PATH", "", 1);

This means that before dropping the arguments to system() the $PATH environment variable is unset. Also the blacklist filter of the previous challenge remains the same. With that only built in sh commands will continue to work and since / is also blacklisted we cannot provide full paths to binaries either. For example id will now not work while pwd still executes:

But the . (or source) command still works. With that we can tell the shell to try to execute the flag.txt file and the error message will reveal its content. We still use the ? wildcard to circumvent the other blacklist by passing . "fl?g.t?t" to it:

The flag is: wpi{p0s1x_sh3Lls_ar3_w13rD}

WPICTF 2018 Shell-JAIL-1

The WPICTF 2018 “Shell-JAIL-1” challenge:

After downloading the linked private key and connecting to the remote server we are dropped into a limited user account and the directory /home/pc_owner. In that folder there are only 3 files – including flag.txt to which our user has no access:

The access file is basically a setuid executable which will run as the pc_owner user. The source of the executable is also available in access.c (mirror here). The program will take all arguments and pass it to system() unless it contains blacklisted strings, relevant parts in the source code:

int filter(const char *cmd){
	int valid = 1;
	valid &amp;= strstr(cmd, "*") == NULL;
	valid &amp;= strstr(cmd, "sh") == NULL;
	valid &amp;= strstr(cmd, "/") == NULL;
	valid &amp;= strstr(cmd, "home") == NULL;
	valid &amp;= strstr(cmd, "pc_owner") == NULL;
	valid &amp;= strstr(cmd, "flag") == NULL;
	valid &amp;= strstr(cmd, "txt") == NULL;
	return valid;
}


int main(int argc, const char **argv){
	setreuid(UID, UID);
	char *cmd = gen_cmd(argc, argv);
	if (!filter(cmd)){
		exit(-1);
	}
	system(cmd);
}

This means passing id to it will work but cat flag.txt will not:

Of course circumventing that filter is rather easy, the * wildcard is forbidden, but ? is not. We can use those wildcards to read flag.txt by passing cat "fla?.tx?" to it:

The flag is: wpi{MaNY_WayS_T0_r3Ad}

Nuit du Hack CTF 2018 CoinGame

The Nuit du Hack CTF 2018 CoinGame challenge:

The URL presented us basically only with a simple webform, which fetches a resource we can specify via cURL:

After a bit of trying, we figured out that file:/// URLs also work, like file:///etc/passwd:

Fetching a lot of files from the server yielded not a lot of success. After a while we noticed the text on the main site: “DESIGNED BY TOTHEYELLOWMOON”

Searching for this and CoinGame a GitHub repo was found: https://github.com/totheyellowmoon/CoinGame
The description of that repo read: “Congrats it was the first step ! Welcome on my Github, this is my new game but I haven’t pushed the modifications …”

From the description of the challenge and the GitHub repo we gather that “CoinGame” is being developed on this server and some changes aren’t pushed yet to the repo.
From /etc/passwd and /var/log/dpkg.log on the server we’ve also figured out that probably a tftp server is running on that system.

Requesting http://coingame.challs.malice.fr/curl.php?way=tftp://127.0.0.1/README.md we found the local repository:

Next we cloned the public GitHub repo, with that we had a list of all existing files in the repository. We looped over all the files and downloaded them via tftp from the system. Then simply ran a diff on the checkout and downloaded files. None of the code had any differences, but a few pictures didn’t match:

In any of the gameAnimationImages/background*.png images the flag was visible:

The flag was: flag{_Rends_L'Arg3nt_!}

iOS camera QR code URL parser bug

I’ve learned recently that the iOS 11 camera app will now automatically scan QR codes and interpret them.
This is pretty cool, until now you needed special apps to do that for you on iOS.
When scanning a QR code which contains a URL – in this case https://infosec.rm-it.de/ –  iOS will show a notification like this:

Naturally the first thing I want to try is to construct a QR code which will show an unsuspicious hostname in the notification but then open another URL in Safari.

And this is exactly what I found after a few minutes. Here it is in action:

There is no redirect misuse being done on facebook.com, Safari will only access infosec.rm-it.de.

Details:

If you scan this QR code with the iOS (11.2.1) camera app:

The URL embedded in the QR code is:
https://xxx\@facebook.com:443@infosec.rm-it.de/

It will show this notification:

But if you tap it to open the site, it will instead open https://infosec.rm-it.de/:

The URL parser of the camera app has a problem here detecting the hostname in this URL in the same way as Safari does.
It probably detects “xxx\” as the username to be sent to “facebook.com:443”.
While Safari might take the complete string “xxx\@facebook.com” as a username and “443” as the password to be sent to infosec.rm-it.de.
This leads to a different hostname being displayed in the notification compared to what actually is opened in Safari.

This issue has been reported to the Apple security team on 2017-12-23.
As of today (2018-03-24) this is still not fixed.

Update:
On 2018-04-24 this has been fixed with iOS 11.3.1 and macOS 10.13.4.
CVE-2018-4187 has been assigned to both issues.

 

NeverLAN CTF 2018 JSON parsing 2

The NeverLAN CTF challenge JSON parsing 1:

The linked file can be found here.

The JSON file contains a minute of VirusTotal scan logs. The challenge wants us to provide a SHA256 hash of a PE resource which most commonly by multiple users. In the data there is the unique_sources field, this will show us which file was uploaded the most by unique users.

Basically I use a short Python script to format the JSON to be easier read and find the highest number of unique_sources, then search the full file for that record.

from pprint import pprint
import json

with open('file-20171020T1500') as f:
    for line in f:
        data = json.loads(line)
        pprint(data)

Running this script like this:

python json2.py |fgrep 'unique_sources' | cut -d ' ' -f 3|sort -n | tail -1

Will find that there is one record with a unique_sources count of 128.
Searching for like this in the full file:

fgrep 'unique_sources": 128' file-20171020T1500

We get the full scan record back, submitting any of the PE resources SHA256 hashes will work as the flag.

NeverLAN CTF 2018 JSON parsing 1

The NeverLAN CTF challenge JSON parsing 1:

The linked file can be found here.

The JSON file contains a minute of VirusTotal scan logs. The challenge wants us to find the 5 AV engines which had the highest detection ratio (not detection count) in that timeframe. To solve it I created this quick Python script:

from __future__ import division
import json

result_true = {}
result_false = {}
result_ratio = {}

with open('file-20171020T1500') as f:
    for line in f:
        data = json.loads(line)
        for scanner in data['scans']:
            if data['scans'][scanner]['detected'] == True:
                if scanner in result_true:
                     result_true[scanner] += 1
                else:
                     result_true[scanner] = 1
            else:
                if scanner in result_false:
                     result_false[scanner] += 1
                else:
                     result_false[scanner] = 1

for scanner in result_false:
    result_ratio[scanner] = result_true[scanner] / (result_true[scanner] + result_false[scanner]) * 100

for key, value in sorted(result_ratio.iteritems(), key=lambda (k,v): (v,k)):
    print "%s: %s" % (key, value)

It will count detection for each AV engine and afterwards calculate the detection ratio for all. Running it will print all ratios sorted by lowest to highest. The last 5 separated by commas is the flag:

The flag is: SymantecMobileInsight,CrowdStrike,SentinelOne,Invincea,Endgame

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}"