Description
Checking whether a file exists or is readable and then reopening its path gives another process time to change which file the path refers to.
Potential impact
In a shared directory, the program could overwrite or read the wrong file. Relying on the earlier access check can expose protected data.
Remediation
- Open and create new files in one operation with
O_CREAT | O_EXCL. Handle errors such as a path that already exists. Read or write through the returned file descriptor. - For temporary files, use a private directory and a dedicated temporary-file API.
Examples
Before
javascript
const fs = require("fs");
const os = require("os");
const path = require("path");
const targetPath = path.join(os.tmpdir(), "report.txt");
if (!fs.existsSync(targetPath)) {
fs.writeFileSync(targetPath, "report");
}
After
javascript
const fs = require("fs");
const os = require("os");
const path = require("path");
const targetPath = path.join(os.tmpdir(), "report.txt");
const fd = fs.openSync(
targetPath,
fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY,
0o600,
);
try {
fs.writeFileSync(fd, "report");
} finally {
fs.closeSync(fd);
}
When fs.openSync succeeds, fs.writeFileSync writes to fd. The finally block closes it even if the write fails. The file report.txt remains in os.tmpdir(), so another exclusive open of that path fails while it exists.