CWE-785 is a C and C++ weakness. The code calls a function that normalizes or resolves a path, and hands it an output buffer smaller than the largest possible result, such as PATH_MAX.
How it happens
Functions such as realpath(), readlink() and PathAppend() write the result into a buffer you supply. MITRE names these directly. If the buffer is smaller than the maximum possible path, a long or crafted path overflows it.
char resolved[64]; /* far below PATH_MAX */
realpath(user_supplied_path, resolved); /* can write past the end */
Developers pick small sizes because most paths are short. Attackers do not send typical paths.
What an attacker gains
The record lists modifying memory, executing unauthorized code or commands, and crashing or restarting the program, along with impacts on confidentiality, integrity and availability. This is a classic buffer overflow with all the usual outcomes. The record has no observed CVEs for this entry.
How to find it
MITRE says static analysis can find some instances. Check by hand:
- Grep for realpath, readlink, PathAppend, GetFullPathName and similar calls.
- For each, find the buffer declaration and confirm its size is at least PATH_MAX or the documented maximum.
- Run with address sanitizer and test with very long paths.
How to fix it
Use a buffer of the documented maximum size, or let the function allocate.
#include <limits.h>
#include <stdlib.h>
char resolved[PATH_MAX];
if (realpath(user_supplied_path, resolved) == NULL) {
/* handle error */
}
With POSIX.1-2008 systems, passing NULL as the second argument makes realpath allocate the result, which you then free. Always check return values and the length your own code adds afterward. Also remember that PATH_MAX is not a guarantee of safety on every system, so avoid copying the result into smaller fixed buffers later.
Quick check
Which functions does MITRE name?
realpath(), readlink() and PathAppend(), among others.