使用堆栈缓冲区溢出(C)

时间:2016-10-13 09:42:52

标签: c stack-overflow stack-smash

我在网上发现了一个有趣的练习,它指出特定的输入可以溢出缓冲区,以便将'秘密'打印到stdout。

我试图通过我自己解决这个问题,但我做得不好。

以下是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void get_name(char *name, char *pr) {
    char local[20];
    printf("%s:",pr);
    gets(local);// BUG
    strncat(name,local,20);
}
int foo () {
    char name[28]="Hello..";
    char secret[12]="TOP SECRET";
    char buf[24];
    char n1[]="Enter your name";
    char n2[]="Enter Secret code"; 
    get_name(name,n1);
    memset(buf, 0, sizeof(buf));
    // Lets ONLY use strncpy for better control!!! 
    strncpy(buf, name, sizeof(buf));//BUG 
    printf("%s\n", buf); 
    memset(name,0,sizeof(name));
    get_name(name, n2);
    if (strncmp(secret,name,10)==0)
        printf("Welcome and %s\n",buf);
    else {printf("Wrong code, better try again..\n");}
    return 0;
}


int main(int argc, char **argv)
{
    foo();
    printf("Bye\n");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

无法知道此类缓冲区溢出的结果。您无法知道或假设他们将覆盖哪些内存。最有可能的是它们只会导致某种运行时崩溃。任何漏洞都必须考虑到非常具体的系统。这意味着在不知道给定系统的细节的情况下,没有人能够回答您的问题。

你的随机互联网用户&#34;的目标是,很可能用一些垃圾覆盖Hello..的空终止,这样"TOP SECRET"字符串就会随之打印出来。但是,您不能假设这两个字符串是相邻分配的。您可以尝试键入28个字母长输入到gets,看看会发生什么......不保证任何给定的行为。在我的电脑上,它除了打印一些垃圾之外没什么兴趣。我的二进制文件的逆向工程揭示了这一点,因为数组确实没有相邻分配。

此外,您对strncpy的评论被误导,strncpy是危险的,应该避免see this

相关问题