getenv() function searches an environment list for a string that matches a specified name and returns a pointer to a string associated with the matched list member.
Subclause 126.96.36.199 of the C Standard [ISO/IEC 9899:2011] states:
The set of environment names and the method for altering the environment list are implementation-defined.
Depending on the implementation, multiple environment variables with the same name may be allowed and can cause unexpected results if a program cannot consistently choose the same value. The GNU glibc library addresses this issue in
setenv() by always using the first variable it encounters and ignoring the rest. However, it is unwise to rely on this behavior.
One common difference between implementations is whether or not environment variables are case sensitive. Although UNIX-like implementations are generally case sensitive, environment variables are "not case sensitive in Windows 98/Me and Windows NT/2000/XP" [MSDN].
Duplicate Environment Variable Detection (POSIX)
The following code defines a function that uses the POSIX
environ array to manually search for duplicate key entries. Any duplicate environment variables are considered an attack, so the program immediately terminates if a duplicate is detected.
Noncompliant Code Example
This noncompliant code example behaves differently when compiled and run on Linux and Microsoft Windows platforms:
On an IA-32 Linux machine with GCC 3.4.4, this code prints
whereas, on an IA-32 Windows XP machine with Microsoft Visual C++ 2008 Express, it prints
Portable code should use environment variables that differ by more than capitalization:
An attacker can create multiple environment variables with the same name (for example, by using the POSIX
execve() function). If the program checks one copy but uses another, security checks may be circumvented.
|Usage of system properties (environment variables) should be restricted|
|SEI CERT C++ Coding Standard||VOID ENV00-CPP. Beware of multiple environment variables with the same effective name|
|ISO/IEC TR 24772:2013||Executing or Loading Untrusted Code [XYS]|
|MITRE CWE||CWE-462, Duplicate key in associative list (Alist)|
CWE-807, Reliance on untrusted inputs in a security decision