Versions Compared

Key

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

Do not make any assumptions about the size of environment variables, as an adversary might have full control over the environment. Calculate If the environment variable needs to be stored, then the length of the strings yourselfassociated string should be calcuated, and dynamically allocate memory for your copies the storage dynamically allocated (see STR31-C. Guarantee that storage for strings has sufficient space for character data and the NULL terminator).

...

This non-compliant code example copies the string returned by getenv() into a fixed size buffer. This can result in a buffer overflow.

Code Block
bgColor#FFcccc
char copy[16];
char *temp = getenv("TEST_ENV");
if (temp != NULL) {
  strcpy(copy, temp);
}

However, the string copied from temp may exceed the size of copy, leading to a buffer overflow.

Compliant Solution

Use In the following compliant solution, the strlen() function is used to calculate the size of the string, and dynamically allocate the required space is dynamically allocated.

Code Block
bgColor#ccccff
char *copy = NULL;
char *temp = getenv("TEST_ENV");
if (temp != NULL) {
  copy = (char *)malloc(strlen(temp) + 1);
  if (copy != NULL) {
    strcpy(copy, temp);
  }
  else {
    /* handle error condition */
  }
}

...