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. Due to the manner in which 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 addresses this issue in getenv() and setenv() by always using the first variable it encounters and ignoring the rest. The POSIX unsetenv() function removes all entries matching the variable name. Other implementations are following suit.

Non-Compliant Code Example

In this non-compliant code example, the getenv function is used to retrieve a value from the environment.

Code Block
bgColor#ffcccc
Code Block
char *temp;
char *copy;

if ((temp = getenv("TEST_ENV")) != NULL) {
  copy = (char *)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;
}

Compliant Solution

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 addresses this issue in getenv() and setenv() by always using the first variable it encounters and ignoring the rest. Other implementations are following suitIt is also possible to search the environment for multiple entries of a variable. On POSIX systems, the environ variable can be used for this purpose. Any duplicate values are an indication of an attack; take appropriate action.

Compliant Solution (POSIX)

In this compliant solution, the environ array is manually searched for duplicate key entries. Any duplicates may indicate an attack.

Code Block
bgColor#ccccff
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() {
  size_t i;
  size_t j;
  size_t k;
  size_t l;
  size_t len_i;
  size_t len_j;

  for(i = 0; environ[i] != NULL; i++) {
    for(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;
}

...