Incorrect use of strncat() may lead to buffer overflow
ID |
c.buffer_overflow.incorrect_use_of_strncat |
Severity |
critical |
Resource |
Buffer Overflow |
Language |
C / C++ |
Description
The strncat() function is nearly as dangerous as strcat(), in that it’s quite easy to misuse. The first common mistake is supplying the size of the entire buffer instead of the size remaining in the buffer. A more subtle mistake can be made: the size parameter needs to be the amount of space left in the buffer less one; otherwise, the NUL byte is written one byte past the end of the buffer.
Rationale
The strncat() function is nearly as dangerous as strcat(), in that it’s quite easy to misuse. The first common mistake is supplying the size of the entire buffer instead of the size remaining in the buffer. A more subtle mistake can be made: the size parameter needs to be the amount of space left in the buffer less one; otherwise, the NUL byte is written one byte past the end of the buffer.
The following code illustrates a vulnerable pattern detected by this rule:
int copy_data(char *username)
{
char buf[1024];
strcpy(buf, "username is: ");
// VULNERABLE: Incorrect use of strncat() may lead to buffer overflow
strncat(buf, username, sizeof(buf));
log("%s\n", buf);
return 0;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.