Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider v2.4 (sch jbop) (X_X)@==(Q_Q)@

...

The actual problem occurs when passing a pointer to an automatic variable to putenv(). An automatic pointer to a static buffer would work as intended.

...

Noncompliant Code Example

Wiki Markup
In this non-compliantnoncompliant code example, a pointer to a buffer of automatic storage duration is used as an argument to {{putenv()}} \[[Dowd 06|AA. C References#Dowd 06]\]. The {{TEST}} environment variable may take on an unintended value if it is accessed once {{func()}} has returned and the stack frame containing {{env}} has been recycled.

...

Code Block
bgColor#FFCCCC
int func(const char const *var) {
  char env[1024];

  if (snprintf(env, sizeof(env),"TEST=%s", var) < 0) {
    /* Handle Error */
  }

  return putenv(env);
}

...

Code Block
bgColor#ccccff
int func(const char const *var) {
  static char *oldenv;
  const char const *env_format = "TEST=%s";
  const size_t const len = strlen(var) + strlen(env_format);
  char *env = (char *) malloc(len);
  if (env == NULL) {
    return -1;
  }
  int rc = snprintf(env, len, env_format, var);
  if (rc < 0 || (size_t)rc >= len) {
    /* Handle Error */
  }
  if (putenv(env) != 0) {
    free(env);
    return -1;
  }
  if (oldenv != NULL)
    free(oldenv); /* avoid memory leak */
  oldenv = env;
  return 0;
}

...

Code Block
bgColor#ccccff
int func(const char const *var) {
  return setenv("TEST", var, 1);
}

...

Fortify SCA Version 5.0 with CERT C Rule Pack is able to can detect violations of this rule.

...