Skip to content

fix(sandbox): bind Windows elevated ACL setup to one no-follow handle (#728) - #765

Merged
Vasanthdev2004 merged 1 commit into
mainfrom
fix/728-windows-acl-toctou
Jul 21, 2026
Merged

Vasanthdev2004 merged 1 commit into
mainfrom
fix/728-windows-acl-toctou

Conversation

@Vasanthdev2004

@Vasanthdev2004 Vasanthdev2004 commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #728.

The bug

The Windows elevated ACL setup resolved each target's pathname independently: os.Stat, then GetNamedSecurityInfo, then SetNamedSecurityInfo (and again by pathname on rollback). Between those calls a lower-privileged local user could swap a target for a symlink or junction, so the elevated process would apply the ACL change to a different object than the one it stat'd and read. That is a TOCTOU across a privilege boundary. The targets are user-influenced (workspace root plus additional write roots) and setup runs elevated, so the local-privesc model is coherent.

The fix

Open each target once with a no-follow handle and drive both the read and the write through it:

  • CreateFile with FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS and READ_CONTROL | WRITE_DAC.
  • GetSecurityInfo(handle) / SetSecurityInfo(handle) instead of the pathname (*Named*) variants, so read and write hit the same kernel object.
  • isDir comes from that handle, not a separate Stat.
  • A target that resolves to a reparse point is refused outright (a setup target that is a symlink/junction during elevated setup is the swap signature).
  • Rollback re-opens no-follow rather than restoring by pathname. The residual window is small (the target is ACL-restricted by then), and I deliberately did not retain handles for the sandbox lifetime because one caller (windows_command_runner_windows.go:114) discards the rollback closure, so retained handles would leak.

Tests

All windows-tagged, no elevation required (the current user holds WRITE_DAC on its own temp dirs):

  • handle-based apply plus rollback round-trip on a temp dir,
  • the materialize-and-remove path,
  • reparse rejection via a junction (needs no admin, so it actually runs in CI, unlike a symlink),
  • the not-exist mapping (so the materialize path still fires).

The full privilege-boundary race cannot be reproduced in CI, so the guard is verified structurally (one handle for read and write) and by junction rejection.

For review

One judgment call worth a maintainer eye: rejecting reparse-point targets assumes setup targets are real directories. If a workspace root is legitimately a junction, that would need revisiting. I went with reject-during-elevated-setup as the safe default.

Verified locally on Windows: go build ./..., go vet ./internal/sandbox/..., and go test ./internal/sandbox/... all clean.

Summary by CodeRabbit

  • Bug Fixes

    • Improved Windows ACL handling to prevent path-related race conditions.
    • Rejects symbolic links, junctions, and other reparse points when applying ACLs.
    • Ensures ACL rollback targets the same underlying file or directory.
    • Preserves correct handling of missing targets and materialized directories.
  • Tests

    • Added coverage for ACL application, rollback, target creation and cleanup, missing paths, files, directories, and reparse points.

Closes #728.

The Windows ACL setup resolved each target's pathname independently across
os.Stat, GetNamedSecurityInfo, and SetNamedSecurityInfo (and again on rollback),
so during elevated setup a lower-privileged local user could swap a target for a
symlink/junction between operations and redirect the ACL change onto a system
object the process never validated. That is a TOCTOU across a privilege boundary.

Open each target once with a no-follow handle (FILE_FLAG_OPEN_REPARSE_POINT plus
FILE_FLAG_BACKUP_SEMANTICS, READ_CONTROL|WRITE_DAC) and drive both the read
(GetSecurityInfo) and the write (SetSecurityInfo) through that one handle, so they
hit the same kernel object. isDir is read from the same handle rather than a
separate Stat. A target that resolves to a reparse point is refused outright,
since a setup target that is a symlink/junction during elevated setup is the
swap-attack signature. Rollback re-opens no-follow rather than restoring by
pathname; the residual window is small because the target is ACL-restricted by
then, and one caller discards the rollback closure so handles are not retained for
the whole sandbox lifetime.

Tests (windows-tagged, no elevation needed): the handle-based apply plus rollback
round-trip on a user-owned temp dir, the materialize-and-remove path, reparse
rejection via a junction (needs no admin, so it runs in CI), and the not-exist
mapping. The full privilege-boundary race can't be reproduced in CI, so the guard
is verified structurally (one handle for read and write) and by junction rejection.
@github-actions

Copy link
Copy Markdown
Contributor

Zero automated PR review

Verdict: No blockers found

Blockers

  • None found.

Validation

  • [pass] Diff hygiene: git diff --check
  • [pass] Tests: go test ./...
  • [pass] Build: go run ./cmd/zero-release build
  • [pass] Smoke build: go run ./cmd/zero-release smoke

Scope

Head: 12d3215fa126
Changed files (2): internal/sandbox/windows_acl_apply_windows.go, internal/sandbox/windows_acl_apply_windows_test.go

This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Changes

Windows ACL handle binding

Layer / File(s) Summary
No-follow target opening and validation
internal/sandbox/windows_acl_apply_windows.go, internal/sandbox/windows_acl_apply_windows_test.go
openWindowsACLTarget opens targets without following reparse points, reports directory status from the handle, preserves missing-target errors, and is covered by Windows-only tests.
Handle-based ACL application
internal/sandbox/windows_acl_apply_windows.go, internal/sandbox/windows_acl_apply_windows_test.go
ACL reads and writes use a single target handle, with cleanup for failures and materialized-target coverage.
Handle-based ACL rollback
internal/sandbox/windows_acl_apply_windows.go
Rollback reopens targets through the protected helper and restores DACLs with SetSecurityInfo.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant applyWindowsACLPathGroup
  participant openWindowsACLTarget
  participant WindowsSecurityAPIs
  participant rollbackWindowsACLSnapshots
  applyWindowsACLPathGroup->>openWindowsACLTarget: Open target without following reparse points
  openWindowsACLTarget-->>applyWindowsACLPathGroup: Return handle and directory status
  applyWindowsACLPathGroup->>WindowsSecurityAPIs: Read and apply DACL through handle
  applyWindowsACLPathGroup-->>rollbackWindowsACLSnapshots: Return ACL snapshot
  rollbackWindowsACLSnapshots->>openWindowsACLTarget: Reopen target safely
  rollbackWindowsACLSnapshots->>WindowsSecurityAPIs: Restore DACL through handle
Loading

Suggested reviewers: jatmn, gnanam1990, kevincodex1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main fix: binding Windows elevated ACL setup to a single no-follow handle.
Linked Issues check ✅ Passed The changes address #728 by using no-follow handles, rejecting reparse points, preserving object identity for apply/rollback, and adding Windows coverage.
Out of Scope Changes check ✅ Passed The PR stays focused on the Windows ACL race fix and related tests, with no obvious unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/728-windows-acl-toctou

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/sandbox/windows_acl_apply_windows.go (1)

236-267: 🔒 Security & Privacy | 🔴 Critical | 🏗️ Heavy lift

Delete materialized rollback targets without re-resolving the path internal/sandbox/windows_acl_apply_windows.go:241
os.RemoveAll(snapshot.Path) still leaves a Windows junction/symlink race; opening and closing the path first only verifies it, it does not make the delete atomic. Use a handle-based no-follow delete path here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/sandbox/windows_acl_apply_windows.go` around lines 236 - 267,
Replace the os.RemoveAll call in rollbackWindowsACLSnapshots for Materialized
snapshots with a handle-based, no-follow deletion operation that removes the
already-opened target without re-resolving snapshot.Path. Reuse the existing
Windows handle/delete helper if available, and preserve the current error
aggregation and reverse-order rollback behavior.
🧹 Nitpick comments (1)
internal/sandbox/windows_acl_apply_windows_test.go (1)

87-107: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Good coverage of the core #728 guard, but only at the openWindowsACLTarget level.

Consider adding a companion case that drives a reparse-point target through applyWindowsACLPathGroup itself (not just openWindowsACLTarget), to pin the end-to-end guarantee that the apply path also refuses to touch a swapped-in target. Since applyWindowsACLPathGroup just propagates openWindowsACLTarget's error via errors.Is(err, os.ErrNotExist) gating, this is largely covered by inspection, but a direct test would catch a future regression in that gating logic itself.

As per path instructions, **/*_test.go should "add regression tests for behavior changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/sandbox/windows_acl_apply_windows_test.go` around lines 87 - 107,
Add a companion regression test for applyWindowsACLPathGroup that creates a
junction or symlink reparse point, invokes the apply path with that target, and
asserts the operation rejects it without touching the target. Reuse the existing
reparse-point setup and verify the propagated error behavior, including the
errors.Is(err, os.ErrNotExist) gating, so regressions in
applyWindowsACLPathGroup are detected independently of openWindowsACLTarget.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/sandbox/windows_acl_apply_windows.go`:
- Around line 236-267: Replace the os.RemoveAll call in
rollbackWindowsACLSnapshots for Materialized snapshots with a handle-based,
no-follow deletion operation that removes the already-opened target without
re-resolving snapshot.Path. Reuse the existing Windows handle/delete helper if
available, and preserve the current error aggregation and reverse-order rollback
behavior.

---

Nitpick comments:
In `@internal/sandbox/windows_acl_apply_windows_test.go`:
- Around line 87-107: Add a companion regression test for
applyWindowsACLPathGroup that creates a junction or symlink reparse point,
invokes the apply path with that target, and asserts the operation rejects it
without touching the target. Reuse the existing reparse-point setup and verify
the propagated error behavior, including the errors.Is(err, os.ErrNotExist)
gating, so regressions in applyWindowsACLPathGroup are detected independently of
openWindowsACLTarget.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0fa7beb4-d9a6-4ea5-8e69-e95495d166e4

📥 Commits

Reviewing files that changed from the base of the PR and between 974fc03 and 12d3215.

📒 Files selected for processing (2)
  • internal/sandbox/windows_acl_apply_windows.go
  • internal/sandbox/windows_acl_apply_windows_test.go

@gnanam1990 gnanam1990 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE. This is the textbook-correct fix for the class of bug #728 describes, and the test coverage is better than most Windows-specific changes get. One scoping question below that I'd like answered rather than changed.

Upfront on method: I can't execute this — it's //go:build windows and I'm on macOS. I cross-compiled (GOOS=windows go build / go vet ./internal/sandbox/ — both clean) and reviewed by reading. Where I had a runtime doubt I leaned on your CI rather than guessing; noted below.

The fix is the right shape

Replacing os.Stat + GetNamedSecurityInfo + SetNamedSecurityInfo — three independent pathname resolutions — with a single CreateFile handle driving GetSecurityInfo/SetSecurityInfo is exactly how you close a TOCTOU on Windows ACL work. The read and the write now provably hit the same kernel object, which is the property that matters and the one pathname-based APIs cannot give you.

Details that are easy to get wrong and aren't:

  • FILE_FLAG_BACKUP_SEMANTICS so directories can be opened at all, alongside FILE_FLAG_OPEN_REPARSE_POINT.
  • READ_CONTROL|WRITE_DAC — the minimal rights for the job, rather than reaching for GENERIC_ALL.
  • The fail closure consolidating cleanup. The previous code repeated if materialized { os.RemoveAll(path) } at five returns; collapsing that into one helper that also closes the handle is what keeps the new early-return paths from leaking. Worth noting it also adds cleanup that was missing before — the materialized-then-open-failed path now removes the target, where the old code returned without it.
  • Rollback re-opens through the same openWindowsACLTarget rather than restoring by pathname, so the restore can't be redirected either. The comment is honest that a window remains and explains why it's acceptable ("the target is ACL-restricted by now"), which I'd much rather read than a claim that it's airtight.

The test coverage is genuinely good

Five real tests, not fakes — and TestOpenWindowsACLTargetRejectsReparsePoint uses mklink /J deliberately because a junction needs neither admin nor Developer Mode, so the security guard actually executes in CI instead of skipping. That's the difference between testing the property and gesturing at it, and Windows smoke is green on this PR, so it really ran.

That also settles the one runtime doubt I had: GetFileInformationByHandle on a handle opened with only READ_CONTROL|WRITE_DAC is the kind of thing that fails with ERROR_ACCESS_DENIED on some configurations, and if it did, every ACL setup would break rather than just the attack path. Your passing Windows job answers that better than I could by reading.

The question: intermediate path components

FILE_FLAG_OPEN_REPARSE_POINT suppresses reparse-point traversal for the final component only. An attacker who can create a junction at a parent directory of an ACL target still redirects the open, and GetFileInformationByHandle on the resulting handle reports the real object's attributes — no reparse-point flag, so the check passes and the ACL lands on the wrong object. Windows has no per-component no-follow for CreateFile; the usual answer is to open the parent chain step-by-step, or to require the whole chain be admin-owned.

So: does the #728 threat model include a lower-privileged user who controls a parent directory of any ACL target? The targets come from entry.Path on WindowsACLEntry, which can include workspace paths, so it depends where those live. If every target sits under an admin-owned root, the residual is unreachable and this is complete as written — worth a sentence in the comment saying so, since the current text scopes the guarantee to "final-component" without saying why that suffices. If workspace paths can sit somewhere another local user can create directories, the guard is a real improvement but not yet a closed boundary, and that's worth a follow-up issue rather than expanding this PR.

Either way this strictly improves on the pathname-based code it replaces, so I don't think it should block.

Verification

GOOS=windows GOARCH=amd64 go build ./internal/sandbox/ and go vet both clean. All nine checks green on the PR, including Windows smoke, which is the job that actually exercises the new code. I did not run the Windows tests locally and am not claiming to have.

Merge is kevin's call per the program gate.

@Vasanthdev2004
Vasanthdev2004 requested a review from anandh8x July 21, 2026 05:11

@anandh8x anandh8x left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on the latest head. ACL reads and writes are bound to one no-follow handle, with reparse-point rejection and rollback coverage. Windows cross-compilation succeeds and all checks are green.

@Vasanthdev2004
Vasanthdev2004 merged commit 4945684 into main Jul 21, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

security(windows): elevated sandbox ACL setup has a path replacement race

3 participants