Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The 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.

Section 7.2022.4.5 of C99 states that 6 of the C standard [ISO/IEC 9899:19992011] states that

The set of environment names and the method for altering the environment list are implementation-defined.

...

Code Block
bgColor#ccccff
langc

extern char **environ;

int main(void) {
  if (multiple_vars_with_same_name()) {
    printf("Someone may be tampering.\n");
    return 1;
  }

  /* ... */

  return 0;
}

int multiple_vars_with_same_name(void) {
  size_t i;
  size_t j;
  size_t k;
  size_t l;
  size_t len_i;
  size_t len_j;

  for(size_t i = 0; environ[i] != NULL; i++) {
    for(size_t j = i; environ[j] != NULL; j++) {
      if (i != j) {
        k = 0;
        l = 0;

        len_i = strlen(environ[i]);
        len_j = strlen(environ[j]);

        while (k < len_i && l < len_j) {
          if (environ[i][k] != environ[j][l])
            break;

          if (environ[i][k] == '=')
            return 1;

          k++;
          l++;
        }
      }
    }
  }
  return 0;
}

...

Code Block
bgColor#ffcccc
langc

if (putenv("TEST_ENV=foo") != 0) {
  /* Handle error */
}
if (putenv("Test_ENV=bar") != 0) {
  /* Handle error */
}

const char *temp = getenv("TEST_ENV");

if (temp == NULL) {
  /* Handle error */
}

printf("%s\n", temp);

On an IA-32 Linux machine with GCC Compiler Version 3.4.4, this code prints

Code Block

foo

whereas, on an IA-32 Windows XP machine with Microsoft Visual C++ 2008 Express, it prints

Code Block

bar

Compliant Solution

Portable code should use environment variables that differ by more than capitalization.

Code Block
bgColor#ccccff
langc

if (putenv("TEST_ENV=foo") != 0) {
  /* Handle error */
}
if (putenv("OTHER_ENV=bar") != 0) {
  /* Handle error */
}

const char *temp = getenv("TEST_ENV");

if (temp == NULL) {
  /* Handle error */
}

printf("%s\n", temp);

...

section

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

Related Vulnerabilities

...

CERT C++ Secure Coding Standard: ENV02-CPP. Beware of multiple environment variables with the same effective name

ISO/IEC 9899:19992011, Section 7.2022.4, "Communication with the Environment"

ISO/IEC TR 24772 "XYS Executing or Loading Untrusted Codeloading untrusted code"

MITRE CWE: CWE-462, "Duplicate Key key in Associative List associative list (Alist)"

MITRE CWE: CWE-807, "Reliance on Untrusted Inputs untrusted inputs in a Security Decisionsecurity decision"

Bibliography

[MSDN] getenv()

...