转载请注明出处:http://blog.youkuaiyun.com/wangxiaolong_china
这里,我们将编写一个非常简单的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/4