Buffer Overflow not happened

2019-01-29 14:59发布

问题:

I tried this sample c code:

int main()
{
    int array[5];
    int i;

    for (i = 0; i <= 255; i++)
    {
        array[i] = 10;
    }
}

and compile it using:

gcc -m32 -o a.out buffer2.c

my question is why there is not Segmentation fault?

i use kali linux 64

vendor_id : GenuineIntel

model name : Intel(R) Core(TM) i3 CPU M 350 @ 2.27GHz

Architecture: x86_64

CPU op-mode(s): 32-bit, 64-bit

Byte Order: Little Endian


I edited code by adding these two lines:

int main()
{
    int x = 12;

    int array[5];
    int i;

    for (i = 0; i <= 255; i++)
    {
        array[i] = 10;
    }

    printf("%d\n", x);
}

and that is the result:

10
Segmentation fault

回答1:

There's no runtime bounds checking in C. Writing to elements outside the bounds of an array is undefined behavior. Undefined behavior means that anything can happen as far as the standard is concerned. So, although a segmentation fault is fairly likely, it's by no means guaranteed.

Just because there wasn't a segmentation fault doesn't mean there wasn't a buffer overflow. There definitely was. It just didn't result in a segmentation fault this time. This type of error is serious and can cause a number of security problems. The moral of the story is don't cause a buffer overflow, ever. It's not safe, and you can't rely on C to protect you.



回答2:

Try:

sudo echo 0 > /proc/sys/kernel/randomize_va_space

And compile again like this:

gcc buffer2.c -o buffer2 -fno-stack-protector