You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

The getenv() function searches an environment list, provided by the host environment, for a string that matches a specified name. Do not rely on the pointer to the string returned by getenv() following a subsequent invocation.

According to C99 [[ISO/IEC 9899-1999]]:

The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function.

This allows an implementation, for example, to copy the environmental variable to an internal static buffer and return a pointer to that buffer.

If you do not immediately make a copy of the value returned by getenv(), but instead store the pointer somewhere for later use, you could end up with a dangling pointer or a different value altogether.

Non-Compliant Coding Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

  char *pwd = getenv("PWD");
  printf("pwd = %s.\n", pwd);
  char *home = getenv("HOME");
  printf("pwd = %s.\n", pwd);
  printf("home = %s.\n", home);

  // see if home is the same as pwd
  if (strcmp(pwd, home) == 0) {
      puts("pwd and home are the same.\n");
  }
  else {
      puts("pwd and home are NOT the same.\n");    
  }

  return 0;

}

Compliant Solution


There is a race condition here even after you call getenv() and before you copy. Be careful to only manipulate the process environment from a single thread at a time.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ENV03-A

2 (high)

2 (probable)

2 (medium)

P8

L2

Examples of vulnerabilities resulting from the violation of this recommendation can be found on the CERT website.

References

[[Dowd 06]] Chapter 10, "UNIX II: Processes"
[[ISO/IEC 9899-1999]] Section 7.20.4, "Communication with the environment"
[[Open Group 04]] Chapter 8, "Environment Variables"
[[Viega 03]] Section 3.6, "Using Environment Variables Securely"
[[Wheeler 03]] Section 5.2, "Environment Variables"

  • No labels