Unsafe use of strlcpy/strlcat return value may cause buffer overflow
ID |
c.buffer_overflow.unsafe_ret_strlcpy_strlcat |
Severity |
low |
Resource |
Buffer Overflow |
Language |
C / C++ |
Description
The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that means the length of the source string. For strlcat() that means the initial length of the destination string plus the length of of the source string. Therefore, this return value can be larger than the size of the destination buffer. If it is used unsafely, e.g. as an index to write to the destination buffer, memory corruption might occur.
Rationale
The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that means the length of the source string. For strlcat() that means the initial length of the destination string plus the length of of the source string. Therefore, this return value can be larger than the size of the destination buffer. If it is used unsafely, e.g. as an index to write to the destination buffer, memory corruption might occur.
The following code illustrates a vulnerable pattern detected by this rule:
void copy_string(char *string)
{
char buf[BUFSIZE];
size_t length;
// VULNERABLE: Unsafe use of strlcpy/strlcat return value may cause buffer overflow
length = strlcpy(buf, string, BUFSIZE);
// use length to access buf, e.g. with strncat()
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.
References
-
OWASP Top 10 2021 - A03 : Injection.