Versions Compared

Key

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

When writing a library, each exposed functions function should perform a validity check on its parameters. Validity checks allow the library to survive at least some forms of improper usage, enabling an application using the library to likewise survive, and often simplifies the task of determining the condition that caused the illegal parameter.

Non-Compliant Coding Example

For these examples, a library exposes an API as followsIn this non-compliant example, setfile() and usefile() do not validate their parameters. It is possible that an invalid file pointer may be used by the library, corrupting the library's internal state and exposing a vulnerability.

Code Block
bgColor#FFcccc
/* sets some internal state in the library */
extern int setfile(FILE *file);

/* performs some action using the file passed earlier */
extern int usefile();

In this non-compliant example, setfile() and usefile() do not validate their parameters. It is possible that an invalid file pointer may be used by the library, corrupting the library's internal state and exposing a vulnerability.

Code Block
bgColor#FFcccc
static FILE *myFile;

int setfile(FILE *file) {
    myFile = file;
    return 0;
}

int usefile() {
    /* perform some action here */
    return 0;
}

...

Validating the function parameters and verifying the internal state leads to consistency of program execution and may eliminate potential vulnerabilities.

Code Block
bgColor#ccccff

/* sets some internal state in the library */
extern int setfile(FILE *file);

/* performs some action using the file passed earlier */
extern int usefile();

static FILE *myFile;

int setfile(FILE *file) {
 if (file && !ferror(file) && !feof(file)) {
    myFile = file;
    return 0;
  }

  myFile = NULL;
  return -1;
}

int usefile() {
  if (!myFile) return -1;

    /* perform other checks if needed, return error condition */

    /* perform some action here */
    return 0;
}

...