Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated references from C11->C23

Some implementations provide a nonportable environment pointer that is valid when main() is called but may be invalidated by operations that modify the environment.

The C Standard, J.5.2 [ISO/IEC 9899:2024], states

In a hosted environment, the main function receives a third argument, char *envp[], that points to a null-terminated array of pointers to char, each of which points to a string that provides information about the environment for this execution of the program (5.1.2.3.2).

Consequently, under a hosted environment supporting this common extension, it is possible to access the environment through a modified form of main():

Code Block
main(int argc, char *argv[], char *envp[]){ /* ... */ }

However, modifying the environment by any means may cause the environment memory to be reallocated, with the result that envp now references an incorrect location. For example, when compiled with GCC 4.8.1 and run on a 32-bit Intel GNU/Linux machine, the following code,

Code Block
#include <stdio.h>
#include <stdlib.h>
 

Under many hosted environments it is possible to access the environment through a modified form of main():

Code Block

main(int argc, char *argv[], char *envp[])

Wiki Markup
According to C99 \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\]:

Wiki Markup
In a hosted environment, the main function receives a third argument, {{char \*envp\[\]}}, that points to a NULL-terminated array of pointers to {{char}}, each of which points to a string that provides information about the environment for this execution of the program.

Wiki Markup
However, modifying the environment by using the {{setenv()}} or {{putenv()}} functions, or by any other means, may cause the environment memory to be reallocated, with the result that {{envp}} now references an incorrect location. For example, \[[Austin Group 08|AA. C References#Austin Group 08]\] says the following.

Unanticipated results may occur if setenv() changes the external variable environ.  In particular, if the optional envp argument to main() is present, it is not changed, and thus may point to an obsolete copy of the environment (as may any other copy of environ).

According to the Microsoft Visual Studio 2005/.NET Framework 2.0 help pages:

The getenv function searches the list of environment variables for varname. getenv is not case sensitive in the Windows operating system. getenv and _putenv use the copy of the environment pointed to by the global variable _environ to access the environment. getenv operates only on the data structures accessible to the run-time library and not on the environment "segment" created for the process by the operating system. Therefore, programs that use the envp argument to main or wmain may retrieve invalid information.

When compiled with gcc-3.4.6 and run on Andrew Linux-2.6.16.29, the following code:

Code Block
extern char **environ;

/* ... */

int main(int argc, const char const *argv[], const char const *envp[]) {
   printf("environ:  %p\n", environ);
   printf("envp:     %p\n", envp);
   setenv("MY_NEW_VAR", "new_value", 1);
   puts("--Added MY_NEW_VAR--");
   printf("environ:  %p\n", environ);
   printf("envp:     %p\n", envp);
  return 0;
}

Yields:yields

Code Block

% ./envp-environ
environ: 0xbf8656ec
envp:    0xbf8656ec
--Added MY_NEW_VAR--
environ: 0x804a008
envp:    0xbf8656ec

It is evident from these results that the environment has been relocated as a result of the call to setenv().

...

. The external variable environ is updated to refer to the current environment; the envp parameter is not.

An environment pointer may also become invalidated by subsequent calls to getenv(). (See ENV34-C. Do not store pointers returned by certain functions for more information.)

Noncompliant Code Example (POSIX)

After a call to the POSIX setenv() function or other to another function that modifies the environment, the envp pointer may no longer reference the current environment. The Portable Operating System Interface (POSIX®), Base Specifications, Issue 7 [IEEE Std 1003.1:2013], states

Unanticipated results may occur if setenv() changes the external variable environ. In particular, if the optional envp argument to main() is present, it is not changed, and thus may point to an obsolete copy of the environment (as may any other copy of environ).

This noncompliant code example accesses the envp pointer after calling setenv():

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, const char const *argv[], const char const *envp[]) {
   size_t i;
   if (setenv("MY_NEW_VAR", "new_value", 1);
 ) != 0) {
    /* Handle error */
  }
  if (envp != NULL) {
      for (size_t i = 0; envp[i] != NULL; i++i) {
         puts(envp[i]);
      }
   }
   return 0;
}

Because envp may no longer points point to the current environment, this program has undefined unanticipated behavior.

Compliant Solution (POSIX)

Use environ in place of envp when defined.:

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
 
extern char **environ;

int main(void) {
  if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
    /* Handle error */
  }
  if (environ != NULL) {
    for (size_t i = 0; environ[i] != NULL; ++i) {
      puts(environ[i]);
    }
  }
  return 0;
}

Noncompliant Code Example (Windows)

After a call to the Windows _putenv_s() function or to another function that modifies the environment, the envp pointer may no longer reference the environment.

According to the Visual C++ reference [MSDN]

The environment block passed to main and wmain is a "frozen" copy of the current environment. If you subsequently change the environment via a call to _putenv or _wputenv, the current environment (as returned by getenv / _wgetenv and the _environ / _wenviron variable) will change, but the block pointed to by envp will not change.

This noncompliant code example accesses the envp pointer after calling _putenv_s():

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
#include <stdlib.h>
  */

int main(int argc, const char *argv[], const char *argv[]envp[]) {
  if (_putenv_s("MY_NEW_VAR", "new_value") != 0) {
    /* Handle error */
  }
  if (envp != NULL) {
    for (size_t i = 0; envp[i] != NULL; ++i) {
      puts(envp[i]);
    }
  }
  return 0;
}

Because envp no longer points to the current environment, this program has unanticipated behavior.

Compliant Solution (Windows)

This compliant solution uses the _environ variable in place of envp:

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
 
_CRTIMP extern char **_environ;

int main(int argc, const char *argv[]) {
  if (_putenv_s  setenv("MY_NEW_VAR", "new_value", 1);
   ) != 0) {
    /* Handle error */
  }
  if (_environ != NULL) {
      for (size_t i = 0; _environ[i] != NULL; i++i) {
         puts(_environ[i]);
      }
   }
   return 0;
}

Note: if you have a great deal of unsafe envp code, you could save time in your remediation by aliasing. Change:

Compliant Solution

This compliant solution can reduce remediation time when a large amount of noncompliant envp code exists. It replaces

Code Block
int 
Code Block

main(int argc, char *argv[], char *envp[]) {

To:

  /* ... */
}

with

Code Block
bgColor#ccccff
langc
#if defined (_POSIX_) || defined (__USE_POSIX)
  
Code Block

extern char **environ;
  #define envp environ

/* ... */
#elif defined(_WIN32)
  _CRTIMP extern char **_environ;
  #define envp _environ
#endif

int main(int argc, char *argv[]) {
  /* ... */
}

This compliant solution may need to be extended to support other implementations that support forms of the external variable environ.

Risk Assessment

Using the envp environment pointer after the environment has been modified may can result in undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ENV31-C

low

Low

unlikely

Probable

low

Medium

P3

L3

P4

L3

Automated Detection

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V
 Supported
Compass/ROSE




Cppcheck Premium
24.9.0
premium-cert-env31-c

Fully implemented

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF4991, DF4992, DF4993


LDRA tool suite
Include Page
LDRA_V
LDRA_V
118 SFully Implemented
Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_C-ENV31-a

Do not rely on an environment pointer following an operation that may invalidate it

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule ENV31-CChecks for environment pointer invalidated by previous operation (rule fully covered)

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Austin Group 08|AA. C References#Austin Group 08]\] vol. 2, System Interfaces, {{setenv()}}
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section J.5.1, "Environment Arguments"

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT CVOID ENV31-CPP. Do not rely on an environment pointer following an operation that may invalidate itPrior to 2018-01-12: CERT: Unspecified Relationship

Bibliography

[IEEE Std 1003.1:2013]XSH, System Interfaces, setenv
[ISO/IEC 9899:2024]J.5.2, "Environment Arguments"
[MSDN]_environ, _wenviron,
getenv, _wgetenv,
_putenv_s, _wputenv_s


...

Image Added Image Added Image AddedENV30-C. Do not modify the string returned by getenv()      10. Environment (ENV)       ENV32-C. No atexit handler should terminate in any way other than by returning