Privileged programs that create files in world-writable directories can overwrite protected system files. An attacker who can predict the name of a file created by a privileged program can create a symbolic link (with the same name as the file used by the program) to point to a protected system file. Unless the privileged program is coded securely, the program will follow the symbolic link instead of opening or creating the file that it is supposed to be using. As a result, a the protected system file to which referenced by the symbolic link points can be overwritten when the program is executed.
Non-Compliant Code Example:
...
fopen()
The following statement creates some_file
in the /tmp
directory.
Code Block | ||
---|---|---|
| ||
intFILE fd*fp = openfopen("/tmp/some_file", O_WRONLY | O_CREAT | O_TRUNC, 0600"w"); |
If /tmp/some_file
already exists then that file is opened and truncated. If /tmp/some_file
is a symbolic link, then the target file referenced by the link is truncated.
To exploit this coding error, an attacker need only create a symbolic link called /tmp/some_file
before execution of this statement.
Non-Compliant Code Example: open()
Wiki Markup |
---|
The {{fopen()}} function does not indicate if an existing file has been opened for writing or a new file has been created. However, the {{open()}} function as defined in the Open Group Base Specifications Issue 6 \[[Open Group 04|AA. C References#Open Group 04]\] provides such a mechanism. If the {{O_CREAT}} and {{O_EXCL |
...
To prevent an existing file from being opened and truncated, include the flags O_CREAT
and O_EXCL
when calling open()
.
}} flags are used together, the {{open()}} function fails when the file specified by {{file_name}} already exists. To prevent an existing file from being opened and truncated, include the flags {{O_CREAT}} and {{O_EXCL}} when calling {{open()}}. |
Code Block | ||
---|---|---|
| ||
int fd = open("/tmp/some_file", O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, 0600); |
...