shellcode之三:shellcode編寫

來源:互聯網
上載者:User

聲明:主要內容來自《The Shellcoder's Handbook》,摘錄重點作為筆記並加上個人的一些理解,如有錯,請務必指出。


系統調用


Shellcode是一組可注入的指令,可在被攻擊的程式內運行。由於shellcode要直接操作寄存器,通常用組合語言編寫並翻譯成十六進位作業碼。我們想讓目標程式以不同與設計折預期的方式運行,操縱程式的方法之一是強制它產生系統調用。


在Linux裡有兩種方法來執行系統調用。間接的方法是libc,直接的方法是用彙編指令調用非強制中斷執行系統調用。在Linux裡,程式通過int 0x80非強制中斷來執行系統調用,調用過程如下:

1、把系統調用編號載入EAX;

2、把系統調用的參數壓入其他寄存器;最多支援6個參數,分別儲存在EBX、ECX、EDX、ESI、EDI和EBP裡;

3、執行int 0x80指令;

4、CPU切換到核心模式;

5、執行系統函數。


如何得到一個shellcode


注意兩點:
1、shellcode應該盡量緊湊,這樣才能注入更小的緩衝區;

2、shellcode應該是可注入的;當攻擊時,最有可能用來儲存shellcode的記憶體地區是為了儲存使用者的輸入而開闢的字元數組緩衝區。因此shellcode不應包含空值(/x00),在字元數組裡,空值是用來終止字串的,空值的存在使得把shellcode複製到緩衝區時會出現異常。


下面以exit()系統調用為例寫一個shellcode。exit()的系統編號為1。用彙編指令實現:

Section .text    global _start_start:    mov ebx,0    mov eax,1    int 0x80

用nasm編譯產生目標檔案,然後用GNU連結器連結目標檔案,最後用objdump顯示相應的作業碼(的標號為_start部分):

sep@debian66:~/shellcode$ nasm -f elf shellcode.asmsep@debian66:~/shellcode$ ld -o shellcode shellcode.o sep@debian66:~/shellcode$ objdump -d shellcodeshellcode: file format elf32-i386Disassembly of section .text:08048080 <_start>: 8048080: bb 00 00 00 00 mov $0x0,%ebx 8048085: b8 01 00 00 00 mov $0x1,%eax 804808a: cd 80          int $0x80sep@debian66:~/shellcode$

shellcode[] = {"/xbb/x00/x00/x00/x00/xb8/x01/x00/x00/x00/xcd/x80"},可以發現裡面出現很多空值,基於shellcode的可注入性,我們需要找出把空值轉換成非空作業碼的方法。有兩種方法:

1、直接用其他具有相同功能的指令替換那些產生空值的指令;

2、在運行時用指令加上空值。


第2個方法比較複雜,暫時先討論第1個方法。根據objdump的結果,發現mov ebx,0和mov eax,1均產生空值。瞭解組合語言的話,可修改為以下代碼:

Section .text    global _start_start:    xor ebx,ebx    mov al,1    int 0x80

編譯、連結、反組譯碼.text段:

sep@debian66:~/shellcode$ nasm -f elf shellcode.asmsep@debian66:~/shellcode$ ld -o shellcode shellcode.o sep@debian66:~/shellcode$ objdump -d shellcodeshellcode: file format elf32-i386Disassembly of section .text:08048080 <_start>: 8048080: 31 db xor %ebx,%ebx 8048082: b0 01 mov $0x1,%al 8048084: cd 80 int $0x80sep@debian66:~/shellcode$

可以看到shellcode的空值消失了,長度也減少了。該shellcode是可注入的。


派生shell


如何寫一個派生shell的shellcode,參考原書P39,這裡不詳述。我現在只需對shellcode的擷取有個大致的瞭解,實現時再看細節。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.