Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack vs heap overflow detection

In a demand paged system like linux where pages maybe~4k from what I read, it ensures protection by checking if the stack or heap size exceeds the number of pages given to each. WHen I create two variables

char *s = (char *) malloc(100);   
char sa[100];

In a for loop I can write s[i] = 'c'; almost 4000 times before it comes up with memory error whereas with sa[i] = 'c'; EDIT: I get a segmentation fault or stack smashing error for anything greater than array size.

I can understand in the first case there is a page fault and it sees that no more pages have been allocated to heap hence a memory violation. But what happens in the second case does gcc keep a check at runtime for all the preallocated variables?.
EDIT: I am posting the entire code below

int main(int argc,char* argv[]){
char *s = (char *) malloc(20);
char sa[400] = {0};
int i ,count;
printf(" enter the number of chars to write: ");
scanf("%d",&count);
for (i=0;i<count;i++){
printf("%d\n",i);
sa[i] = 'a';
//s[i] = 'a';
}
free(s);

}
like image 522
dasman Avatar asked Aug 14 '11 09:08

dasman


1 Answers

On a lot of 32-bit operating systems the stack grows downwards. You only use positive indexes into the array so it depends how deeply nested your function call is. As you index out of the array, you'll first overwrite the canary. So the stack smashing error is first. Next, you'll start overwriting the function arguments and return address. Without the canary, that will cause the function return to jump into nevernever land, usually producing a segfault. Not always, it might accidentally land on valid code, the logic behind stack buffer overflow attacks.

As you keep going, you'll eventually write past the top of the stack into unallocated pages. Segfault then. On a small test program with few nested calls that happens quickly, couple of kilobytes give or take.

Also try it with negative offsets. That can keep going for a while, not otherwise causing any mishap since you're writing into unallocated stack space. The segfault comes when you write past the allocated stack size, typically a megabyte. On Windows you'd trigger the stack guard page, generating an exception for which this site is named.

like image 94
Hans Passant Avatar answered Oct 05 '22 12:10

Hans Passant