Buffer overflows usually stem from code that has been badly written and not included the necessary checks to prevent them.
Vulnerable code:
#includeTo compile this code use this commandint main(){ char buffer[5]; char a[2]; char b[2]; printf("Enter a string: "); gets(buffer); printf("Contents of buffer:%s\n",buffer); printf("Contents of a:%c\n",a); printf("Contents of b:%c\n",b); }
gcc bufferOverflow.c -fno-stack-protectorNow lets try inputting 5 characters:
Enter a string:aaaaa Contents of buffer:aaaaa Contents of a: Contents of b:At the moment it is running well without any errors and not overflowing into the variables a and b, this is because we are not exceeding the size of the buffbuffer overflower.
Lets increase it to 6:
Enter a string:aaaaa Contents of buffer:aaaaa Contents of a: Contents of b:a and b are still empty.
After some trial and error I managed to write into the variable b using 15 characters.
Enter a string: aaaaaaaaaaaaaaa Contents of buffer:aaaaaaaaaaaaaaa Contents of a: Contents of b:aUsing 16 characters I have managed to indirectly write into the memory which holds the values of a and b.
If you input more characters at some point you will cause a segmentation fault as the program is trying to access memory that it doesn't have access to.
Enter a string: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Contents of buffer:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Contents of a:a Contents of b:a Segmentation fault (core dumped)To fix the code we need to change the gets function to fgets.
#includeNow no matter what we enter to the program it will never write more characters than the size of the buffer to the buffer.int main(){ char buffer[5]; char a; char b; printf("Enter a string: "); fgets(buffer, sizeof(buffer), stdin); printf("Contents of buffer:%s\n",buffer); printf("Contents of a:%c\n",a); printf("Contents of b:%c\n",b); }
Enter a string: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Contents of buffer:aaaa Contents of a: Contents of b:Only 4 characters are printed as fgets includes the newline character at the end of the input.
No comments:
Post a comment