潜在的文件系统竞争条件¶
ID: js/file-system-race
Kind: problem
Security severity: 7.7
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-367
Query suites:
- javascript-security-extended.qls
- javascript-security-and-quality.qls
通常需要在使用文件之前检查其状态。这些检查通常会接受要检查的文件名,如果检查结果为真,则会打开该文件或对其执行其他操作。
但是,在检查和操作之间的时间内,攻击者可能会更改文件名引用的底层文件,从而导致意外行为。
建议¶
尽可能使用文件描述符而不是文件名。
示例¶
以下示例显示了一种情况,代码检查`/tmp/`文件夹中是否存在文件,如果不存在,则将文件写入该位置。
const fs = require("fs");
const os = require("os");
const path = require("path");
const filePath = path.join(os.tmpdir(), "my-temp-file.txt");
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "Hello", { mode: 0o600 });
}
但是,在多用户环境中,另一个用户可能在存在检查和写入之间创建了该文件。
这可以通过使用`fs.open`获取文件描述符,然后在写入操作中使用该文件描述符来避免。
const fs = require("fs");
const os = require("os");
const path = require("path");
const filePath = path.join(os.tmpdir(), "my-temp-file.txt");
try {
const fd = fs.openSync(filePath, fs.O_CREAT | fs.O_EXCL | fs.O_RDWR, 0o600);
fs.writeFileSync(fd, "Hello");
} catch (e) {
// file existed
}
参考资料¶
维基百科:检查时到使用时.
针对 C 的 CERT Oracle 安全编码标准: FIO01-C. 注意使用使用文件名进行标识的函数 .
NodeJS:FS 模块.
常见漏洞枚举:CWE-367.