strcat
Prototype
char* strcat(char* dest, const char* src);
This function appends a copy of the string pointed to by src
(including the terminating null character) to the end of the string pointed to by dest
. The dest
array must be large enough to hold the combined strings, including the terminating null character.
Vulnerable example
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer[10];
strlcpy(buffer, argv[1], sizeof(buffer));
// The strcat function concatenates the second string to the end of the first
// string. It does not check for buffer overflows, so if the first string is
// not large enough to hold the second string, it will write beyond the bounds
// of the buffer, potentially leading to a buffer overflow vulnerability.
strcat(buffer, argv[2]);
printf("%s\n", buffer);
return 0;
}
Prevent
To prevent this vulnerability, use the strlcat
function instead of strcat
to concatenate the second string to the end of the buffer
string.
The strlcat
function allows to specify the maximum number of characters to be copied from the source string and ensure that the destination string is always null-terminated , which can help to prevent the destination buffer from being overrun with data.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer[10];
strlcpy(buffer, argv[1], sizeof(buffer));
strlcat(buffer, argv[2], sizeof(buffer) - strlen(buffer) - 1);
printf("%s\n", buffer);
return 0;
}
Last updated