Insecure temporary file creation

Insecure temporary file creation

Description

Writing a fixed filename in a shared directory such as os.tmpdir() can collide with an existing file or symbolic link. This may expose temporary data or overwrite another file, depending on the application’s permissions and how the file is used.

Potential impact

  • Other users may read temporary logs, tokens, or sensitive data.
  • A pre-created symlink may redirect writes to important configuration or key files.
  • Modified files that are later executed or loaded may enable code execution or privilege escalation.
  • Filename collisions or permission errors may interrupt temporary work or service availability.

Remediation

  • Prefer a secret store for tokens and private keys. If a temporary file is necessary, use a reviewed library such as tmp or create a private directory under os.tmpdir() with fs.mkdtemp or mkdtempSync.
  • Create files inside a directory other users cannot modify. Use 'wx' or 'ax' to reject an existing path, and restrict permissions, for example to 0o600. Avoid passing a fixed shared path directly to fs.writeFile, fs.writeFileSync, or fs.createWriteStream.
  • Verify ownership and permissions as needed, then remove the files and directory after use.

Examples

Before

javascript
const fs = require("fs");
const os = require("os");
const path = require("path");

function saveReport(data) {
  // Before: write a predictable name directly in shared TMP
  const p = path.join(os.tmpdir(), "report.txt");
  fs.writeFileSync(p, data); // Default permissions/flags may allow races or excessive access
  return p;
}

After

javascript
const fs = require("fs");
const os = require("os");
const path = require("path");
const crypto = require("crypto");

function saveReportSafely(data) {
  // 1) Create a unique temporary directory with a random suffix
  const base = path.join(os.tmpdir(), "myapp-");
  const tmpDir = fs.mkdtempSync(base); // Example: /tmp/myapp-abc123

  // 2) Use a random filename inside the directory to avoid collisions
  const name = "report-" + crypto.randomBytes(8).toString("hex") + ".log";
  const filePath = path.join(tmpDir, name);

  // 3) Fail if the path exists and create with minimal permissions
  fs.writeFileSync(filePath, data, { flag: "wx", mode: 0o600 });

  return filePath;
  // Clean up after use with fs.rmSync(tmpDir, { recursive: true, force: true }); as needed
}

The revised function creates a new directory and filename for each report. The wx flag prevents overwriting an existing path. The function returns the path, so the caller must remove the file and directory after use.

References