Wiki Markup |
---|
The C99 \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] C standard function {{fopen()}} is typically used to open an existing file or create a new one. However, {{fopen()}} does not indicate if an existing file has been opened for writing or a new file has been created. This may lead to a program overwriting or accessing an unintended file. |
Non-Compliant Code Example: fopen()
...
Wiki Markup |
---|
However, this code suffers from a _Time of Check, Time of Use_ (or _TOCTOU_) vulnerability (see \[[Seacord 05|AA. C References#Seacord 05]\] Section 7.2). On a shared multitasking system there is a window of opportunity between the first call of {{fopen()}} and the second call for a malicious attacker to, for example, create a link with the given filename to an existing file, so that the existing file is overwritten by the second call of {{fopen()}} and the subsequent writing to the file. |
...
Code Block | ||
---|---|---|
| ||
/* ... */ int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, new_file_mode); if (fd == -1) { /* Handle Error */ } /* ... */ |
Wiki Markup |
---|
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, in particular the {{EXCLUSIVE}} value to the {{mode}} argument of {{CREATE}} \[[Callaghan 95|AA. C References#Callaghan 95]\]. |
Compliant Solution: fdopen()
(POSIX)
...