Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

從C源碼到機器碼:shellcode提取入門實踐

本文以一個最經典的教學案例為切入點:編寫一段能彈出命令列(shell)的shellcode,並演示如何從C源碼出發,一步步還原、分析並最終提取出可用的機器碼。

起點:一段簡短的C程式

整個流程從下面這段C程式開始。它構造了一個參數陣列,然後呼叫execve去執行/bin/bash:

  1. root@linux:~/pentest# cat shellcode.c
  2. #include <stdio.h>
  3. int main(int argc, char **argv){
  4.   char *name[2];
  5.   name[0] = "/bin/bash";
  6.   name[1] = NULL;
  7.   execve(name[0], name, NULL);
  8.   return 0;
  9. }

靜態編譯,排除鏈接干擾

為了避免動態鏈接引入的額外依賴,我們採用靜態方式編譯,並保留除錯符號:

root@linux:~/pentest# gcc -static -g -o shellcode shellcode.c

用GDB反編譯分析

接著用gdb載入程式並反編譯main函式,觀察編譯器實際產生的組語:

  1. root@linux:~/pentest# gdb shellcode
  2. (gdb) disass main
  3. Dump of assembler code for function main:
  4.  0x080482c0 <+0>: push %ebp
  5.  0x080482c1 <+1>: mov %esp,%ebp
  6.  0x080482c3 <+3>: and $0xfffffff0,%esp
  7.  0x080482c6 <+6>: sub $0x20,%esp
  8.  0x080482c9 <+9>: movl $0x80ae428,0x18(%esp)
  9.  0x080482d1 <+17>: movl $0x0,0x1c(%esp)
  10.  0x080482d9 <+25>: mov 0x18(%esp),%eax
  11.  0x080482dd <+29>: movl $0x0,0x8(%esp)
  12.  0x080482e5 <+37>: lea 0x18(%esp),%edx
  13.  0x080482e9 <+41>: mov %edx,0x4(%esp)
  14.  0x080482ed <+45>: mov %eax,(%esp)
  15.  0x080482f0 <+48>: call 0x8052f10 <execve>
  16.  0x080482f5 <+53>: mov $0x0,%eax
  17.  0x080482fa <+58>: leave
  18.  0x080482fb <+59>: ret
  19. End of assembler dump.

從反編譯結果可以看出,在call指令執行之前,函式堆棧上已經按execve的呼叫約定擺放好了三個參數:可執行路徑字串、參數陣列以及空環境變數指標。下圖示意了此時的堆棧佈局:

動態驗證分析結論

我們用gdb實際運行程式,在main入口與execve呼叫前各下一個斷點,逐步檢視堆棧內容,以確認上面的靜態分析是否正確:

  1. (gdb) b main
  2. Breakpoint 1 at 0x80482c9: file shellcode.c, line 6.
  3. (gdb) b *main+48
  4. Breakpoint 2 at 0x80482f0: file shellcode.c, line 9.
  5. (gdb) r
  6. Breakpoint 1, main (argc=1, argv=0xbffff474) at shellcode.c:6
  7. (gdb) x/s 0x80ae428
  8. 0x80ae428: "/bin/bash"
  9. (gdb) c
  10. Breakpoint 2, 0x080482f0 in main (argc=1, argv=0xbffff474) at shellcode.c:9
  11. (gdb) x/4bx $ebp-40
  12. 0xbffff3b0: 0x28 0xe4 0x0a 0x08
  13. (gdb) x/4bx $ebp-36
  14. 0xbffff3b4: 0xc8 0xf3 0xff 0xbf
  15. (gdb) x/4bx $ebp-32
  16. 0xbffff3b8: 0x00 0x00 0x00 0x00
  17. (gdb) x/4bx $ebp-12
  18. 0xbffff3cc: 0x00 0x00 0x00 0x00
  19. (gdb) x/4bx $ebp-16
  20. 0xbffff3c8: 0x28 0xe4 0x0a 0x08

透過這些記憶體傾印可以清楚看到:字串"/bin/bash"的地址被放入陣列首元素,第二個元素為NULL,環境變數指標同樣為0,與靜態反編譯的推斷完全吻合。掌握這一層堆棧佈局,是後續手工構造shellcode的關鍵基礎。

Copyright © Linux教程網 All Rights Reserved