...
In this noncompliant code example, setfile() and usefile() do not validate their parameters. It is possible that an invalid file pointer can be used by the library, corrupting the library's internal state and exposing a vulnerability.
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* 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;
void setfile(const FILE *file) {
myFile = file;
}
void usefile(void) {
/* perform some action here */
}
|
...
Validating the function parameters and verifying the internal state leads to consistency of program execution and may eliminate potential vulnerabilities. In addition, implementing commit/rollback semantics (leaving program state unchanged on error) is a desirable practice for error safety.
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* 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;
errno_t setfile(FILE *file) {
if (file && !ferror(file) && !feof(file)) {
myFile = file;
return 0;
}
/* error safety: leave myFile unchaned */
return EINVAL;
}
errno_t usefile(void) {
if (!myFile) return -1;
/* perform other checks if needed, return
* error condition */
/* perform some action here */
return 0;
}
|
...