...
| Code Block |
|---|
int rename(const char *old, const char *new); |
If the file pointed to referenced by new exists prior to a call to calling rename(), the behavior is implementation-defined. ThereforeFor portability, care must be taken when using you must ensure that the file referenced by new does not exist when rename() is invoked.
Non-Compliant Code Example
In the following this non-compliant code example, a file is renamed to another file moved using rename().
| Code Block | ||
|---|---|---|
| ||
/* program code */
const char *old = "oldfile.ext";
const char *new = "newfile.ext";
if (rename(old, new) != 0) {
/* Handle rename failure */
}
/* program code */
|
However, if If newfile.ext already existed exists at the time of the call to rename(), the result is undefinedimplementation-defined.
Compliant Solution
This compliant solution first checks for the existence of the new file before the call to callling rename(). Note that this This code contains an unavoidable race condition between the call to fopen() and the call to rename(). Consequently, this code can only be safely executed within a secure directory.
| Code Block | ||
|---|---|---|
| ||
/* program code */
const char *old = "oldfile.ext";
const char *new = "newfile.ext";
FILE *file = fopen(new, "r");
if (file != NULL) {
fclose(file);
if (rename(old, new) != 0) {
/* Handle remove failure */
}
}
else {
/* handle error condition */
}
/* program code */
|
Risk Assessment
Using Calling rename() without caution leads to undefined behavior, possibly resulting has implementation-defined behavior when the new file name refers to an existing file. Incorrect use of rename could result in a file being unexpectedly overwritten or other unexpected behavior.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FIO10-A | 2 (medium) | 2 (probable) | 2 (medium) | P8 | L2 |
...