Versions Compared

Key

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

...

This noncompliant code example invokes the C99 system() function to execute the /bin/ls program. The C99 system() function passes a string to the command processor in the host environment to be executed.

Code Block
bgColor#ffcccc
langc
if (system("/bin/ls dir.`date +%Y%m%d`") == -1) {
  /* Handle error */
}

...

In this compliant solution, the environment is cleared by clearenv(), and then the PATH and IFS variables are set to safe values before system() is invoked. Sanitizing a shell command can be difficult and doing so can adversely affect the power and flexibility associated with them.

Code Block
bgColor#ccccff
langc
char *pathbuf;
size_t n;

if (clearenv() != 0) {
  /* Handle error */
}

n = confstr(_CS_PATH, NULL, 0);
if (n == 0) {
  /* Handle error */
}

if ((pathbuf = malloc(n)) == NULL) {
  /* Handle error */
}

if (confstr(_CS_PATH, pathbuf, n) == 0) {
  /* Handle error */
}

if (setenv("PATH", pathbuf, 1) == -1) {
  /* Handle error */
}

if (setenv("IFS", " \t\n", 1) == -1) {
  /* Handle error */
}

if (system("ls dir.`date +%Y%m%d`") == -1) {
  /* Handle error */
}

...

On systems that have no clearenv() function, the following implementation can be used:

Code Block
bgColor#ccccff
langc
extern char **environ;

int clearenv(void) {
  static char *namebuf = NULL;
  static size_t lastlen = 0;

  while (environ != NULL && environ[0] != NULL) {
    size_t len = strcspn(environ[0], "=");
    if (len == 0) {
      /* Handle empty variable name (corrupted environ[]) */
    }
    if (len > lastlen) {
      namebuf = realloc(namebuf, len+1);
      if (namebuf == NULL) {
        /* Handle error */
      }
      lastlen = len;
    }
    memcpy(namebuf, environ[0], len);
    namebuf[len] = '\0';
    if (unsetenv(namebuf) == -1) {
      /* Handle error */
    }
  }
  return 0;
}

...