繁体   English   中英

C 缓冲区溢出获取分段错误

[英]C buffer overflow getting Segmentation Fault

我正在尝试为我的安全 class 做一个缓冲区溢出,我们不允许调用任何 function,我们需要在没有分段错误的情况下跳转到秘密 function 并返回。 我编写了下面的代码并成功跳转到秘密,但我遇到了分段错误。 如何成功终止程序? 或者是否可以只写入单个地址而不是 for 循环,当我尝试时它没有改变任何东西。

#include <stdio.h>

void secret()
{
    printf("now inside secret()!\n");
}

void entrance()
{
    int doNotTouch[10];
    // can only modify this section BEGIN
    // cant call secret(), maybe use secret (pointer to function)
    for (int i = 0; i < 14; i++) {
        *(doNotTouch + i) = (int) &secret;
    }
    // can only modify this section END
    printf("now inside entrance()!\n");
}

int main (int argc, char *argv[])
{
    entrance();
    return 0;
}

在一些半汇编程序中,假设某种 x86。 (BP 是 EBP 或 RBP 的伪代码,假设您实际上并未针对 16 位模式进行编译。32 位模式很可能因此int与返回地址的宽度相同。)

; entrance:
; - stack has return address to main
push  bp                         ; decrement SP by a pointer width
mov   bp,sp
sub   sp, 10*sizeof(int)         ; reserve space for an array
;....
; doNotTouch[0] is probably at [bp - 10*sizeof(int)]

当您循环到 14 时,您首先在 i==10 处覆盖保存的 bp,然后将返回地址覆盖到 main(这是正确的),然后再覆盖一些最终导致 seg 错误的地址。 所以你只需要做*(doNotTouch + 11) = (int) &secret; - 假设 int 是 function 指针的大小。 (或者如果编译器为堆栈对齐或它自己的使用留下了间隙。在调试构建中,其他本地人将有堆栈插槽。覆盖它们可能会导致无限循环超出范围。)

然后跟随您的 printf 然后 function 返回,但它不会返回 main 而是“跳转”到secret

secret返回时,实际上是从main返回,但不能return 0;

所以秘密应该是:

int secret()
{
    printf("now inside secret()!\n");
    return 0;
}

免责声明:“....我认为。”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM