| Wiki Markup |
|---|
The POSIX function {{putenv()}} is used to set environment variable values. The {{putenv()}} function does not create a copy of the string supplied to it as an argument,; rather, it inserts a pointer to the string into the environment array. If a pointer to a buffer of automatic storage duration is supplied as an argument to {{putenv()}}, the memory allocated for that buffer may be overwritten when the containing function returns and stack memory is recycled. This behavior is noted in the Open Group Base Specifications Issue 6 \[[Open Group 04|AA. C References#Open Group 04]\]: |
...
The actual problem occurs when passing a pointer to an automatic variable to putenv(). An automatic pointer to a static buffer would work as intended.
...
The setenv() function allocates heap memory for environment variables. This eliminates the possibility of accessing volatile , stack memory.
| Code Block | ||
|---|---|---|
| ||
int func(char const *var) {
return setenv("TEST", var, 1);
}
|
Using setenv() is easier, and consequently , less error prone, than using (putenv()).
...
Using a pointer to a buffer of automatic storage duration as an argument to putenv() may cause that buffer to take on an unintended value. Depending on how and when that the buffer is used, this can cause unexpected program behavior, or possibly allow an attacker to run arbitrary code.
...