Destination buffer of getwd or realpath is
smaller than PATH_MAX bytes
This defect occurs when the destination
argument of a path manipulation function such as realpath or getwd has
a buffer size less than PATH_MAX bytes.
A buffer smaller than PATH_MAX bytes can
overflow but you cannot test the function return value to determine
if an overflow occurred. If an overflow occurs, following the function
call, the content of the buffer is undefined.
For instance, char *getwd(char *buf) copies
an absolute path name of the current folder to its argument. If the
length of the absolute path name is greater than PATH_MAX bytes, getwd returns NULL and
the content of *buf is undefined. You can test
the return value of getwd for NULL to
see if the function call succeeded.
However, if the allowed buffer for buf is
less than PATH_MAX bytes, a failure can occur for
a smaller absolute path name. In this case, getwd does
not return NULL even though a failure occurred.
Therefore, the allowed buffer for buf must be PATH_MAX bytes
long.
Possible fixes are:
Use a buffer size of PATH_MAX bytes.
If you obtain the buffer from an unknown source, before using the
buffer as argument of getwd or realpath function,
make sure that the size is less than PATH_MAX bytes.
Use a path manipulation function that allows you to specify a buffer size.
For instance, if you are using getwd to get
the absolute path name of the current folder, use char *getcwd(char
*buf, size_t size); instead. The additional argument size allows
you to specify a size greater than or equal to PATH_MAX.
Allow the function to allocate additional memory dynamically, if possible.
For instance, char *realpath(const char *path, char
*resolved_path); dynamically allocates memory if resolved_path is NULL.
However, you have to deallocate this memory later using the free function.
| Group: Static memory |
| Language: C | C++ |
| Default: Off |
Command-Line Syntax: PATH_BUFFER_OVERFLOW |
| Impact: High |
| CWE ID: 785 |