...
A potential error is to call
putenv()with an automatic variable as the argument, then return from the calling function while string is still part of the environment.
Non-Compliant Code Example
In this example derived from Dowd, an automatic variable is used to modify the environment via a call to putenv(). When that environment variable is retrieved, it may have a value that is different than the value supplied to putenv(). Note that this example also violates rule DCL30-C. Do not refer to an object outside of its lifetime.
| Code Block | ||
|---|---|---|
| ||
int func(char *var) {
char env[1024];
if (snprintf(env, sizeof(env),"ENV=%s", var) < 0) {
/* Handle Error */
}
putenv(env);
return 0;
}
|
Compliant Solution
To make this example compliant env should not be declared as an automatic variable.
| Code Block | ||
|---|---|---|
| ||
int func(char *var) {
static char env[1024];
if (snprintf(env, sizeof(env),"ENV=%s", var) < 0) {
/* Handle Error */
}
putenv(env);
return 0;
}
|
Risk Assessment
Using an automatic variable as an argument to putenv() may cause that variable to take on an unintended value. Depending on how and when that variable is used, this can cause unexpected program behavior, or possibly allow an attacker to run arbitrary code.
...
Examples of vulnerabilities resulting from the violation of this rule can be found on the CERT website.
References
| Wiki Markup |
|---|
\[[Open Group 04|AA. C++ References#Open Group 04]\] The putenv() function \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.4, "Storage durations of objects," and Section 7.20.3, "Memory management functions" \[[Dowd|AA. C References#Dowd 06]\] \[[DCL30-C. Do not refer to an object outside of its lifetime]\] |