這裡,我們將編寫一個非常簡單的shellcode,它的功能是得到一個命令行。我們將從該shellcode的C程序源碼開始,逐步構造並提取shellcode。
該shellcode的C程序源碼為:
- root@linux:~/pentest# cat shellcode.c
- #include <stdio.h>
-
- int main(int argc, char **argv) {
-
- char *name[2];
- name[0] = "/bin/bash";
- name[1] = NULL;
-
- execve(name[0], name, NULL);
-
- return 0;
- }
為了避免鏈接干擾,靜態編譯該shellcode,命令為:
root@linux:~/pentest# gcc -static -g -o shellcode shellcode.c
下面使用gdb調試並分析一下shellcode程序:
- root@linux:~/pentest# gdb shellcode
- GNU gdb (Ubuntu/Linaro 7.2-1ubuntu11) 7.2
- Copyright (C) 2010 Free Software Foundation, Inc.
- License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
- This is free software: you are free to change and redistribute it.
- There is NO WARRANTY, to the extent permitted by law. Type "show copying"
- and "show warranty" for details.
- This GDB was configured as "i686-linux-gnu".
- For bug reporting instructions, please see:
- <http://www.gnu.org/software/gdb/bugs/>...
- Reading symbols from /root/pentest/shellcode...done.
- (gdb) disass main
- Dump of assembler code for function main:
- 0x080482c0 <+0>: push %ebp
- 0x080482c1 <+1>: mov %esp,%ebp
- 0x080482c3 <+3>: and {1}xfffffff0,%esp
- 0x080482c6 <+6>: sub {1}x20,%esp
- 0x080482c9 <+9>: movl {1}x80ae428,0x18(%esp)
- 0x080482d1 <+17>: movl {1}x0,0x1c(%esp)
- 0x080482d9 <+25>: mov 0x18(%esp),%eax
- 0x080482dd <+29>: movl {1}x0,0x8(%esp)
- 0x080482e5 <+37>: lea 0x18(%esp),%edx
- 0x080482e9 <+41>: mov %edx,0x4(%esp)
- 0x080482ed <+45>: mov %eax,(%esp)
- 0x080482f0 <+48>: call 0x8052f10 <execve>
- 0x080482f5 <+53>: mov {1}x0,%eax
- 0x080482fa <+58>: leave
- 0x080482fb <+59>: ret
- End of assembler dump.
根據程序反匯編得到的代碼分析,在call指令執行之前,函數堆棧的使用情況如下圖所示:
我們用gdb調試運行shellcode,看我們上面的分析是否完全正確。
- (gdb) b main
- Breakpoint 1 at 0x80482c9: file shellcode.c, line 6.
- (gdb) b *main+48
- Breakpoint 2 at 0x80482f0: file shellcode.c, line 9.
- (gdb) r
- Starting program: /root/pentest/shellcode
-
- Breakpoint 1, main (argc=1, argv=0xbffff474) at shellcode.c:6
- 6 name[0] = "/bin/bash";
- (gdb) x/s 0x80ae428
- 0x80ae428: "/bin/bash"
- (gdb) c
- Continuing.
-
- Breakpoint 2, 0x080482f0 in main (argc=1, argv=0xbffff474) at shellcode.c:9
- 9 execve(name[0], name, NULL);
- (gdb) x/4bx $ebp-40
- 0xbffff3b0: 0x28 0xe4 0x0a 0x08
- (gdb) x/4bx $ebp-36
- 0xbffff3b4: 0xc8 0xf3 0xff 0xbf
- (gdb) x/4bx $ebp-32
- 0xbffff3b8: 0x00 0x00 0x00 0x00
- (gdb) x/4bx $ebp-12
- 0xbffff3cc: 0x00 0x00 0x00 0x00
- (gdb) x/4bx $ebp-16
- 0xbffff3c8: 0x28 0xe4 0x0a 0x08
- (gdb)