CXX.PUTENV.LOCAL.PTR

Do not pass a pointer to a local variable in the putenv()

The putenv() function provided by POSIX is used to configure the environment. However, passing a pointer to a local variable to set an environment variable causes undefined behavior.

Vulnerability and risk

The putenv() function is used to set environment variables. The putenv() function inserts the pointer into the environment variable array without making a copy of the variable passed in as an argument. Therefore, when using a pointer to a local variable, there is a possibility of deallocating and reusing memory that points to that variable's value. In this case, it can also override the values used in the configuration. But passing a pointer to a static variable with a static lifetime is no problem.

Mitigation and prevention

To prevent this, provide a static variant of the object.

Vulnerable code example

Copy
int func_good(const char *var)
{ 
        char env[1024];
        int retval = snprintf(env, sizeof(env), "TEST=%s", var);
        if (retval < 0 || (size_t)retval >= sizeof(env)) {
                /* Handle error */
        }
        return putenv(env);
}

In the code above, we pass the local variable env to the putenv() function. However, the env local variable is deallocated after the func() function ends. This causes the pointer introduced by the putenv() function to the environment variable array to point to a memory address that is no longer relevant.