C语言高级编程:利用堆栈溢出修改函数返回地址
生活随笔
收集整理的這篇文章主要介紹了
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.exeAddress 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=10040116dAddress of param=0xffffcb10 Address of ret=0x10040116d Address of local value=0xffffcaf8 i am in funok, i did it.可見看到通過對fun函數返回地址的修改,成功執行了bad_fun()
?
分析:
1)要實現本功能主要要實現以下兩點:
-
計算fun函數入參input到fun局部變量buf的長度(字節),由此便可以知道返回返回地址相對于buf的偏移,因為ret地址就在函數入參input的下方
-
利用buf數組來修改ret地址
2)測試系統為小端模式
3)測試系統為64位,所以需要注意函數地址為64位(8字節長),而不是32位。另外寄存器也是8字節長。
4)堆棧結構如下
?
?
?
?
總結
以上是生活随笔為你收集整理的C语言高级编程:利用堆栈溢出修改函数返回地址的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言高级编程:大端模式和小端模式(Bi
- 下一篇: 中国邮政储蓄银行绿卡通是什么卡