Unsafe use of snprintf and vsnprintf return values
Description
The snprintf() and vsnprintf() functions return the total length of the string they tried to create, which can be larger than the size of the destination buffer. Using this return value unsafely, e.g., as an index to write to the destination buffer, can cause memory corruption.
Examples
Insecure Code
c
int len = snprintf(buf, 10, "Hello, %s!", user_input); buf[len] = '\0';Secure Code
c
int len = snprintf(buf, 10, "Hello, %s!", user_input); if (len >= 10) { /* handle error */ } else { buf[len] = '\0'; }Remediation
Check the return value of snprintf() and vsnprintf() to ensure it does not exceed the size of the destination buffer before using it.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0744 |
| Category | Injection |
| Severity | MEDIUM |
| CWE | CWE-120 |
| Confidence | MEDIUM |
| Impact | HIGH |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | buffer overflow, memory corruption |
| OWASP | N/A |
References
- https://g.co/kgs/PCHQjJ
- https://dustri.org/b/playing-with-weggli.html
- https://lwn.net/Articles/507319/