Skip to content

[Bug]: atomic replacement chmods the caller-supplied path after rename, following a swapped symlink #86

Closed

Description

@yetval

Summary

replaceFileAtomic and replaceFileAtomicSync reach the caller-requested mode with a chmod on the caller-supplied filePath after the rename has already completed. A local user who can write the parent directory can unlink the replacement path in that window and drop a symlink in its place. chmod follows the symlink, so the mode change lands on an unrelated file the caller never named. Both entry points are affected.

The temp file cannot carry the requested mode on its own, because it is created with writeFile(tempPath, content, { mode, flag: "wx" }), so its mode is reduced by the process umask. The post-rename chmod is the only thing that reaches the exact mode, and no option disables it.

Minimal reproduction

Requested mode 0o600, umask 077, an unrelated file at 644 in the same tree. The destination entry is replaced with a symlink to that file immediately after the rename lands.

import fs from "node:fs";
import fsp from "node:fs/promises";
import { replaceFileAtomic } from "@openclaw/fs-safe/atomic";

const realRename = fsp.rename.bind(fsp);
fsp.rename = async (src, dest) => {
  await realRename(src, dest);
  await fsp.unlink(dest);
  await fsp.symlink(victim, dest);   // attacker wins the post-rename window
};

await replaceFileAtomic({ filePath: target, content: "new", dirMode: 0o700, mode: 0o600 });
console.log((fs.lstatSync(victim).mode & 0o777).toString(8));   // 600, was 644

Only rename is wrapped, and it performs the real rename first. Everything else is the real filesystem, so the chmod that follows is a real fs.chmod on a real symlink. The same reproduction with replaceFileAtomicSync and fs.renameSync behaves identically.

Expected behavior

The requested mode is applied to the object the caller wrote, and only to it. A destination entry swapped after rename is never followed.

Actual behavior

The requested mode is applied to whatever the destination path resolves to at chmod time, which the caller does not control. An unrelated file goes from 644 to 600 with no error and nothing logged.

Package version or commit

main at 2477f5681f6882a385b02702360010f5adf7bf1a. Reproduced against the published 0.5.0 package. v0.5.1 is the newest tag and carries the same code.

Affected surface

src/replace-file.ts, both entry points.

Async path:

    await assertDestinationHardlinkPolicy(fsModule, filePath, options.destinationHardlinks);
    const result = await renameWithRetry({ /* ... */ });
    tempExists = false;
    unregisterTempPath();
    await fsModule.chmod(filePath, mode).catch(() => undefined);   // line 371

Sync path:

    tempExists = false;
    unregisterTempPath();
    try {
      fsModule.chmodSync(filePath, mode);                          // line 437
    } catch {
      // Best-effort on platforms that do not enforce POSIX modes.
    }

assertDestinationHardlinkPolicy and the caller's beforeRename hook both run before the rename, so destination tampering is already treated as in scope. The chmod is the one operation that happens after it, on a path rather than on a descriptor, and it escapes every check above it.

The SUPPORTS_NOFOLLOW / OPEN_READ_FLAGS hardening added in 0.4.7 does not cover this. It applies only inside the copy fallback, where the destination is opened with sourceStat.mode & 0o777, which is the umask-reduced temp mode, so the exact requested mode is still only reachable via the by-path chmod.

replaceDirectoryAtomic and movePathWithCopyFallback were checked. The restore paths in src/replace-file-copy-fallback.ts work on descriptors opened with OPEN_READ_FLAGS / OPEN_WRITE_EXCLUSIVE_FLAGS rather than a by-path chmod, so they do not have this shape. The dirMode chmod targets a directory the library just created and is not part of this report.

Environment

Node.js 24, Linux, ext4, default mount options, process umask 077.

Redacted logs or filesystem evidence

See the proof block below.

Impact

Any consumer that passes mode for a path in a directory another local user can write hands that user an arbitrary-file chmod primitive.

openclaw/openclaw re-exports replaceFileAtomic verbatim through src/infra/replace-file.ts and src/plugin-sdk/security-runtime.ts, and pins 0.5.0 at 807506381a0362a748e01e28839f15a38a4a911e. Two callers pass a mode today:

  • extensions/whatsapp/src/creds-persistence.ts writes the WhatsApp web credentials with mode: 0o600, dirMode: 0o700. It already passes a beforeRename hook that re-asserts the destination is a regular file or missing, which shows the intent, and that hook does not cover the post-rename window.
  • src/secrets/shared.ts:66 writeTextFileAtomic writes secret-adjacent text files with a default 0o600.

Suggested remediation

Set the mode on the temp file descriptor before the rename and drop the by-path chmod entirely. The temp path is library-owned and not attacker-reachable under a tempPrefix the caller does not publish, and fchmod takes no path at all. The reference run below reaches the requested 600 exactly this way under umask 077, with the destination swap still staged.

ReplaceFileAtomicBaseOptions currently exposes no way for a consumer to opt out of the post-rename chmod, so this cannot be worked around downstream without wrapping the injected fileSystem and intercepting chmod, which couples the consumer to library internals across versions.

Real behavior proof

Behavior addressed: the atomic replacement helpers apply the caller-requested mode to a symlink swapped into the destination path after rename, changing the mode of an unrelated file.
Real environment tested: the real published @openclaw/fs-safe 0.5.0 package, driven through the real consumer module src/infra/replace-file.ts from openclaw/openclaw at 807506381a0362a748e01e28839f15a38a4a911e, against real on-disk directories under a real umask of 077, using the exact option set extensions/whatsapp/src/creds-persistence.ts passes including its real beforeRename assertion. Only fsp.rename and fs.renameSync were wrapped: each performs the real rename and then stages the swap at that exact boundary, so the chmod that follows is a real fs.chmod on a real symlink. chmod calls were recorded to show which paths receive them.
Exact steps or command run after this patch: node --import tsx openclaw-driver.mts from a checkout at 807506381a0362a748e01e28839f15a38a4a911e with @openclaw/fs-safe resolved to 0.5.0.
Evidence after fix:

# OBSERVED (@openclaw/fs-safe 0.5.0, both entry points)
whatsapp creds path async: victim mode before save: 644
whatsapp creds path async: chmod paths: <parent>,creds.json
whatsapp creds path async: victim mode after save: 600
secrets path sync: victim mode before write: 644
secrets path sync: chmod paths: <parent>,creds.json
secrets path sync: victim mode after write: 600

# EXPECTED (mode set on the temp descriptor before rename, no by-path chmod)
reference ordering: victim mode before write: 644
reference ordering: chmod paths: <parent>
reference ordering: victim mode after write: 644
reference ordering: mode reached before rename: 600

Observed result after fix: on 0.5.0 the recorded chmod path list includes the destination path itself, and the unrelated operator file silently drops from 644 to 600 on both the async and the sync entry point. With the mode set on the temp descriptor before rename, the list contains only the parent directory, the unrelated file keeps 644, and the requested 600 is still reached exactly under umask 077.
What was not tested: no live multi-process attacker race was staged, so this does not measure how wide the real window is in wall-clock terms. The swap is performed deterministically at the rename boundary. Behavior on Windows and on filesystems without POSIX modes was not exercised. The copy fallback branch was not driven, since it does not reach the by-path chmod.

Activity

  1. added
    P1
    impact:security
    issue-rating: 🦞 diamond lobster
    clawsweeper:source-repro
    clawsweeper:no-new-fix-pr
    clawsweeper:needs-security-review
    on Aug 2, 2026
  2. clawsweeper commented on Aug 2, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed August 2, 2026, 2:47 PM ET / 18:47 UTC.

    Summary
    The reported post-rename pathname chmod remains in current main and the shipped v0.5.1, so this security report is still necessary and should stay open for maintainer-led remediation.

    Reproducibility: yes. —current source provides a high-confidence path: both APIs rename the temporary file and then chmod the caller-controlled destination pathname. The issue also supplies a deterministic rename-boundary swap mechanism, but this read-only review did not execute it.

    Maintainer decision needed

    Question Recommendation
    Should the package adopt a descriptor-lifetime change for both atomic replacement APIs now, including any compatible expansion of the injectable filesystem interface needed to preserve exact modes before rename? Coordinate descriptor-bound repair: Preserve the existing mode contract by setting the mode on the opened temporary file before rename and add deterministic regressions for both APIs.

    Why: The defect is source-proven, but changing file-descriptor ownership and the public test filesystem contract across async and sync APIs is a security-boundary and compatibility decision that should be coordinated by the area owner.

    Next step
    The protected security-triage state and descriptor-lifetime compatibility boundary require maintainer-led coordination rather than an autonomous repair PR.

    Security
    Needs attention: Current main contains a concrete post-rename pathname permission change that can follow a swapped symlink in both atomic replacement APIs.

    Review details

    Best possible solution:

    Implement a coordinated security fix that writes and applies the final mode through the same temporary-file descriptor before publication, removes destination-path chmod calls, and adds deterministic async and sync symlink-swap regressions under a restrictive umask.

    Do we have a high-confidence way to reproduce the issue?

    Yes—current source provides a high-confidence path: both APIs rename the temporary file and then chmod the caller-controlled destination pathname. The issue also supplies a deterministic rename-boundary swap mechanism, but this read-only review did not execute it.

    Is this the best way to solve the issue?

    Yes, in direction: bind the mode change to the temporary file descriptor before rename and remove the post-rename pathname chmod. The implementation must also preserve the documented exact-mode behavior and existing fallback and injected-filesystem contracts.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • A safe repair must keep the requested exact mode despite umask while removing both post-rename pathname chmod calls.
    • Changing to descriptor-bound mode setting affects the public injectable filesystem contract and must cover the normal rename and copy-fallback paths without weakening existing identity checks.

    Codex review notes: model internal, reasoning high; reviewed against 2477f5681f68.

    Label changes

    Label justifications:

    • P1: A caller using the atomic-write mode option in a shared writable parent can have an unrelated file’s permissions changed through a deterministic rename-boundary swap.
    • impact:security: The report concerns a symlink and rename identity-swap race that redirects a permission-changing operation to an unintended file.
    Evidence reviewed

    Security concerns:

    • [high] Bind final mode changes to the temporary file object — src/replace-file.ts:371
      After rename, both APIs chmod filePath, so a local writer who replaces that entry with a symlink can redirect the requested mode to an unrelated target. Set the mode through the temporary file descriptor before publication and remove the path-based calls.
      Confidence: 0.99

    What I checked:

    • Current async path remains vulnerable: Current main writes the temporary file, completes rename, then performs a best-effort chmod on the caller-supplied destination pathname; a symlink swap between those operations can redirect the mode change. (src/replace-file.ts:371, 2477f5681f68)
    • Current sync path has the same ordering: The synchronous API likewise writes the temporary file, renames it, and then calls chmodSync on filePath, leaving the same post-rename pathname boundary. (src/replace-file.ts:437, 2477f5681f68)
    • Published release still carries the behavior: The affected lines blame to the v0.5.1 release commit, and v0.5.1 is an ancestor of current main; the current release therefore has not yet fixed this report. (src/replace-file.ts:371, 16e1bd489ae8)
    • Public contract promises mode preservation: The atomic-write documentation exposes mode as the explicit mode for the new file and documents an injectable filesystem surface, so the repair must preserve exact-mode semantics and compatibility for that test interface. (docs/atomic.md:40, 2477f5681f68)
    • Repository policy treats this race class as security-sensitive: The repository policy explicitly names symlink, rename, and identity-swap races that cross a documented filesystem boundary as in scope, and requires fail-closed behavior around ambiguous identity states. (SECURITY.md:17, 2477f5681f68)

    Likely related people:

    • Peter Steinberger: The current affected lines blame to the v0.5.1 release commit and the available history shows repeated ownership of src/replace-file.ts, including the atomic-replace hardening work. (role: recent atomic-write area contributor; confidence: high; commits: 16e1bd489ae8, 66e59e0ce95e; files: src/replace-file.ts, test/atomic.test.ts, docs/atomic.md)
    How this review workflow works
    • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
    • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
    • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
    • Maintainers can also comment @clawsweeper review to request a fresh review only.
    • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
    • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1clawsweeper:needs-security-reviewclawsweeper:no-new-fix-prclawsweeper:source-reproimpact:securityissue-rating: 🦞 diamond lobster

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions