...
The fopen_s()
function defined in ISO/IEC TR 24731-1-2007 is designed to improve the security of the fopen()
function. However, like fopen()
, fopen_s()
provides no mechanism to determine if an existing file has been opened for writing or a new file has been created. The code below contains the same TOCTOU race condition as in the first Non-Compliant Code Examplenon-compliant code example using fopen()
.
Code Block | ||
---|---|---|
| ||
/* ... */ FILE *fptr; errno_t res = fopen_s(&fptr,"foo.txt", "r"); if (res != 0) { /* file does not exist */ res = fopen_s(&fptr,"foo.txt", "w"); /* ... */ fclose(fptr); } else { fclose(fptr); } /* ... */ |
...
Care should be observed when using O_EXCL
with remote file systems as it does not work with NFS version 2. NFS version 3 added support for O_EXCL
mode in open()
; see IETF RFC 1813 Callaghan 95, in particular the EXCLUSIVE
value to the mode
argument of CREATE
Callaghan 95.
Compliant Solution: fdopen()
(POSIX)
Wiki Markup |
---|
For code that operates on {{FILE}} pointers and not file descriptors, the POSIX {{fdopen()}} function \[[Open Group 04|AA. C References#Open Group 05]\] can be used into conjunctionassociate withan {{open()}} tostream determinewith if athe file isdescriptor openedreturned or createdby {{open()}}, andas thenshown associatein athis stream with the file descriptorcompliant solution. |
Code Block | ||
---|---|---|
| ||
/* ... */
FILE *fp;
int fd;
fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, new_file_mode);
if (fd == -1) {
/* Handle Error */
}
fp = fdopen(fd, "w");
if (fp == NULL) {
/* Handle Error */
}
/* ... */
|
...
The ability to determine if an existing file has been opened , or a new file has been created provides greater assurance that the intended file accessed is the one that was intendedis accessed, or perhaps more importantly, a file other than the intended file is not acted upon.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO03-A | 2 (medium) | 2 (probable) | 1 (high) | P4 | L3 |
...