Versions Compared

Key

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

When writing a library, each exposed 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 invalid parameter.

Non-Compliant

...

Code Example

In this non-compliant code 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();

static FILE *myFile;

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

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

The vulnerability may be more severe if the internal state references sensitive or system-critical data.

...

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;

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

  myFile = NULL;
  return -1INVALID_ARG;
}

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

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

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

...

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

References

Wiki Markup
Apple, Inc. Secure Coding Guide: Application Interfaces That Enhance Security. Retrieved Apr 26, 2007
\[[Apple 06|AA. C References#Apple 06]\] [Application Interfaces That Enhance Security|http://developer.apple.com/documentation/Security/Conceptual/SecureCodingGuide/Articles/AppInterfaces.html], May 2006.

...

MSC07-A. Detect and remove dead code      13. Miscellaneous (MSC)       MSC09-A. Character Encoding - Use Subset of ASCII for Safety