In this post we will talk about how one of the oldest computer attacks occurs: buffer overflow.
A buffer overflow occurs when a program has reserved an amount of memory X for a variable in the memory space, but at the time of assigning its value, the value has a size greater than X.
What happens in this situation is that, if the program does not control well the amount of data that is copied, what does not fit in the reserved space will be written in adjacent memory cells.
A malicious user could use this in his favor to alter other variables whose assigned memory area is contiguous to the one that produces the buffer overflow. Let’s see a simple example:
The above code, written in C, receives by argument a password, copies it into a buffer, and compares whether that buffer is equal to “lethani“. If it is, a message appears that root privileges have been granted to the user.
A priori this code seems correct, but let’s see what happens if you enter some passwords…
Root privileges have been granted, despite entering the wrong password. This phenomenon is the buffer overflow, by entering more characters than the buffer variable had reserved in memory, the strcpy function has continued to write in the logOK variable, overwriting 1 by 0, and therefore granting root privileges.
This is just a simple example to demonstrate how buffer overflow works. To avoid this, it would simply be enough to use the strncpy function instead of the strcpy function, since in strncpy you have to indicate the size you want to enter in the variable.
This type of attack is very old, it was discovered in 1988 when the Morris worm appeared, because it was one of the attacks that was used to spread. The Morris worm was a malware that was replicated on 6000 of the 60,000 servers that were connected to the network at that time, including NASA’s navigation center. In addition to this, other very famous worms such as Code Red or SQL Slammer have taken advantage of the buffer overflow.
This attack goes beyond being able to overwrite a variable. Having a buffer overflow vulnerability, it is possible to make sure that the address being overwritten corresponds to a real one, and thus include instructions in the buffer to execute malicious code (or even execute a shell).
To make sure your code is not vulnerable to buffer overflow, don’t use dangerous functions like strcpy or strcmp.