[英]Buffer overflow example with gcc
我试图演示C的strcmp
strcpyV.c
缓冲区溢出。我有strcpyV.c
文件:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char a[8];
char b[8];
// function causes buffer overflow
strcpy(b, "01234567");
// buffer overflow again
strcpy(a, "89abcdef");
printf("\nb = %s\n", b);
return 0;
}
我使用gcc编译器编译该程序。
gcc -o strcpyV strcpyV.c
当我在树莓派B +(Raspbian wheezy)中执行此操作并运行时:
./strcpyV
我得到了预期的结果:
b = 0123456789abcdef
但是当我在Ubuntu 16.04中执行此整个过程时,结果是:
b = 01234567
没有这种内存保护,有什么办法可以编译代码?
您可以将数组打包为一个结构。 然后适用于struct打包的规则。 该标准未定义struct打包规则,但是如果使用gcc
,则在这种情况下char数组将是连续的(请注意b
现在放在a
之前):
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct ab {
char b[8];
char a[8];
} s;
// function causes buffer overflow
strcpy(s.b, "01234567");
// I removed this buffer overflow by making the string fit.
// A second overflow doesn't add anything - quite the opposite.
// The first overflow is sufficient to get the
// behaviour you want.
strcpy(s.a, "89abcde");
printf("\nb = %s\n", s.b);
return 0;
}
您可以禁用安全检查:
从手册中:
-fstack-protector
Emit extra code to check for buffer overflows, such as stack smashing attacks. >This is done by adding a guard variable to functions with
vulnerable objects. This includes functions that call alloca, and functions with >buffers larger than 8 bytes. The guards are initialized when
a function is entered and then checked when the function exits. If a guard check >fails, an error message is printed and the program exits.
-fstack-protector-all
Like -fstack-protector except that all functions are protected.
如果您要禁用此功能,只需在选项名称中输入no-
-fno-stack-protector -fno-stack-protector-all
缓冲区溢出示例:
int main(){
int valid = 0;
char str1 = ["START"];
char str2 = [8];
gets(str2);
if(strncmp(str1, str2, 8) == 0){
valid = 1;
cout << "buffer: " << str1 << ", " << str2 << ", " << valid << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.