The getenv()
function searches an environment list, provided by the host environment, for a string that matches a specified name. The getenv()
function returns a pointer to a string associated with the matched list member. Due to the way environment variables are stored, multiple environment variables with the same name can cause unexpected results.
Implementation Details
Depending on the implementation, a program may not consistently choose the same value if there are multiple environment variables with the same name. The GNU glibc library attempts to deal with this issue in getenv()
and setenv()
by always using the first variable it comes across, and ignoring the rest. unsetenv()
will remove all the entries matching the variable name.
Non-Compliant Coding Example
Do not search or modify environ
directly. Using a stable function such as getenv()
or setenv()
will prevent this issue.
Compliant Solution
char *temp; char *copy; if ((temp = getenv("TEST_ENV")) != NULL) { copy= malloc(strlen(temp) + 1); if (copy != NULL) strcpy(copy, temp); else /* handle error condition */ copy[0] = 'a'; setenv("TEST_ENV", copy, 1); } else { return -1; }
Risk Assessment
An adversary could create several environment variables with the same name. If the program checks against one copy, but actually uses another, this could be a clear problem.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
ENV02-A |
3 (high) |
1 (low) |
1 (high) |
P3 |
L3 |
References
[[ISO/IEC 9899-1999:TC2]] Section 7.20.4, "Communication with the environment"