Main Content

Use of path manipulation function without maximum-sized buffer checking

Destination buffer of getwd or realpath is smaller than PATH_MAX bytes

Description

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.

Risk

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.

Fix

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.

Examples

expand all

#include <unistd.h>
#include <linux/limits.h>
#include <stdio.h>

void func(void) {
    char buf[PATH_MAX];
    if (getwd(buf+1)!= NULL)         {
        printf("cwd is %s\n", buf);
    }
}

In this example, although the array buf has PATH_MAX bytes, the argument of getwd is buf + 1, whose allowed buffer is less than PATH_MAX bytes.

Correction — Use Array of Size PATH_MAX Bytes

One possible correction is to use an array argument with size equal to PATH_MAX bytes.

#include <unistd.h>
#include <linux/limits.h>
#include <stdio.h>

void func(void) {
    char buf[PATH_MAX];
    if (getwd(buf)!= NULL)         {
        printf("cwd is %s\n", buf);
    }
}

Result Information

Group: Static memory
Language: C | C++
Default: Off
Command-Line Syntax: PATH_BUFFER_OVERFLOW
Impact: High

Version History

Introduced in R2015b