开发者

Not getting a segmentation fault when expecting it

开发者 https://www.devze.com 2023-03-18 05:35 出处:网络
I\'m toying with buffer overflows, but I\'m confused by what I\'m finding when running the following simple C program on Mac OS.

I'm toying with buffer overflows, but I'm confused by what I'm finding when running the following simple C program on Mac OS.

#include <stdio.h>

int main(void) {

        char buf[2];

        scanf("%s", buf);

        printf("%s\n", buf);

}

By setting the length of bu开发者_如何学编程f to 2 bytes, I expected to cause a segmentation fault when entering the string "CCC", but that doesn't happen. Only when entering a string 24 characters in length do I incur a segmentation fault.

What's going on? Is it something to do with character encoding?

Thanks.


The behavior of your program is undefined as soon as you overflow the buffer. Anything can happen. You can't predict it.

There might or might not be some padding bytes after your buffer that happen to be unimportant to your code execution. You can't rely on that. A different compiler, compiling in 32bit vs 64bit, debug settings... all that could alter your code execution after that overflow.


Because buf is on the stack. When you start overwriting it, you start overwriting the stack which belongs to the program which the OS won't catch depending on what else is allocated there (e.g. spill slots for registers created by the compiler). Only once you cross the allocated stack boundary the OS will have a chance to raise a segfault.


I guess it's related to the memory layout. If what you are overwriting is accessible to your process (a page mapped writable) the OS doesn't have a chance to see you're doing something "wrong".

Indeed, when doing something like this, from the eyes of a C programmer "that's totally wrong!". But in the eyes of the OS "Okay, he's writing stuff to some page. Is the page mapped with the adequate permissions ? If it is, OKAY".


There is no guarantee that you will get segmentation fault at all. There is more data after char buf[2] overwriting it may or may not cause segmentation fault.


buf is allocated on the stack, you're just overwriting an area that's not used there is a good chance that nobody will complain about it. On some platforms your code will accept whole paragraphs.

0

精彩评论

暂无评论...
验证码 换一张
取 消