Labels

Arduino (1) Brainf**k (1) Bugs (3) C (1) HTML (1) Install (3) Linux (27) Maths (1) Python (12) Raspberry Pi (4)

Saturday, 10 December 2016

Buffer Overflow Variable writing in C



Buffer overflows usually stem from code that has been badly written and not included the necessary checks to prevent them.



Vulnerable code:
#include
int 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);
}
To compile this code use this command
gcc bufferOverflow.c -fno-stack-protector
Now 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:a
Using 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.
#include
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);
}
Now no matter what we enter to the program it will never write more characters than the size of the buffer to the buffer.
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.