feat(sandbox): Windows sandbox principals (foundation for #662, does not close it) - #808
Vasanthdev2004 wants to merge 129 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds Windows sandbox principal provisioning, protected secret storage, handle-relative ACL enforcement, deterministic runtime roots, network coverage checks, Git protections, and the ChangesWindows sandbox security and execution
Priority: ➖ Normal Estimated code review effort: 5 (Critical) | ~120 minutes Severity of issue fixed: Medium Merge Risk: 🟠 High · up to The Windows sandbox changes still carry material security, filesystem, and command-availability risks. In particular, elevated operations may alter unintended paths, ACL planning can create the wrong object type, and valid sandbox commands may be refused. These issues should be resolved before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Linked Issues checkExplanation The PR provides substantial provisioning, ACL, secret-storage, and runtime foundations for Resolution Implement and validate a supported command-launch mechanism for the sandbox principal, or another default Windows confinement mechanism. Ensure sandboxed commands cannot read the credential stores listed in Full details: Out of Scope Changes checkExplanation The PR includes changes beyond the linked issue and principal foundation, including the new sandbox CLI command, nested Git initialization policy, signal-handling behavior, and the unrelated exported peermsg directory helper.
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/sandbox/windows_identity_logon_windows.go (2)
48-54: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsolidate the five separate
advapi32.dlllazy loads.Five independent
windows.NewLazySystemDLL("advapi32.dll")calls wherewindows_identity_windows.gouses a single sharednetapi32var for its DLL and derives procs from it. Mirroring that pattern here is cheap and keeps the two files consistent.♻️ Proposed refactor
-var ( - procLogonUserW = windows.NewLazySystemDLL("advapi32.dll").NewProc("LogonUserW") - procLsaOpenPolicy = windows.NewLazySystemDLL("advapi32.dll").NewProc("LsaOpenPolicy") - procLsaClose = windows.NewLazySystemDLL("advapi32.dll").NewProc("LsaClose") - procLsaAddAccountRights = windows.NewLazySystemDLL("advapi32.dll").NewProc("LsaAddAccountRights") - procLsaNtStatusToWinErr = windows.NewLazySystemDLL("advapi32.dll").NewProc("LsaNtStatusToWinError") -) +var ( + advapi32 = windows.NewLazySystemDLL("advapi32.dll") + procLogonUserW = advapi32.NewProc("LogonUserW") + procLsaOpenPolicy = advapi32.NewProc("LsaOpenPolicy") + procLsaClose = advapi32.NewProc("LsaClose") + procLsaAddAccountRights = advapi32.NewProc("LsaAddAccountRights") + procLsaNtStatusToWinErr = advapi32.NewProc("LsaNtStatusToWinError") +)🤖 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_identity_logon_windows.go` around lines 48 - 54, Consolidate the five independent advapi32.dll lazy loads in the proc declarations around procLogonUserW, procLsaOpenPolicy, procLsaClose, procLsaAddAccountRights, and procLsaNtStatusToWinErr by defining one shared lazy DLL variable and deriving each procedure from it, matching the shared-DLL pattern used by the neighboring Windows identity implementation.
195-203: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRedundant/fragile "keep alive" idiom repeated across both files.
Both files independently reinvent a "keep the buffer alive after the syscall" step, but the object is already retained through the call by the compiler's special-case handling of
uintptr(unsafe.Pointer(x))appearing in the.Call()argument list (perunsafepackage docs, this also applies toLazyProc.Callon Windows), and pointer fields nested inside that object are reachable transitively via normal GC tracing. None of these five sites add real protection, and if protection were ever genuinely needed,_ = buffer[0]/_ = infois not the guaranteed primitive for it —runtime.KeepAliveis.
internal/sandbox/windows_identity_logon_windows.go#L195-L203: replace theruntimeKeepAliveUint16helper with a directruntime.KeepAlive(buffer)call at each use (or drop it, since the buffer is already protected viaentryin the.Call()argument).internal/sandbox/windows_identity_logon_windows.go#L150-L152: swapruntimeKeepAliveUint16(buffer)forruntime.KeepAlive(buffer), or remove the line.internal/sandbox/windows_identity_windows.go#L202-L204: dropdefer func(){_=info}()inensureWindowsSandboxGroup, or replace withdefer runtime.KeepAlive(&info)if you want to keep the intent explicit.internal/sandbox/windows_identity_windows.go#L239: same for theinfodefer inensureWindowsSandboxUser.internal/sandbox/windows_identity_windows.go#L262: same for theentrydefer inaddWindowsSandboxUserToGroup.🤖 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_identity_logon_windows.go` around lines 195 - 203, Remove the redundant fragile keep-alive idioms and rely on the syscall argument retention; in internal/sandbox/windows_identity_logon_windows.go:150-152 and :195-203, remove runtimeKeepAliveUint16 and its uses (or replace each with runtime.KeepAlive(buffer) if explicit intent is retained). In internal/sandbox/windows_identity_windows.go:202-204, :239, and :262, remove the defer closures referencing info or entry, or replace them with defer runtime.KeepAlive(&info) / defer runtime.KeepAlive(&entry) respectively.
🤖 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.
Inline comments:
In `@internal/sandbox/windows_identity_acl.go`:
- Around line 85-91: Validate each value in ProtectedMetadataNames before
constructing the WindowsACLEntry, accepting only a single non-empty path
component and rejecting empty values, "."/"..", and any value containing path
separators. Do not call filepath.Join for rejected names; add tests covering
traversal and separator-containing inputs while preserving valid-name
materialization.
---
Nitpick comments:
In `@internal/sandbox/windows_identity_logon_windows.go`:
- Around line 48-54: Consolidate the five independent advapi32.dll lazy loads in
the proc declarations around procLogonUserW, procLsaOpenPolicy, procLsaClose,
procLsaAddAccountRights, and procLsaNtStatusToWinErr by defining one shared lazy
DLL variable and deriving each procedure from it, matching the shared-DLL
pattern used by the neighboring Windows identity implementation.
- Around line 195-203: Remove the redundant fragile keep-alive idioms and rely
on the syscall argument retention; in
internal/sandbox/windows_identity_logon_windows.go:150-152 and :195-203, remove
runtimeKeepAliveUint16 and its uses (or replace each with
runtime.KeepAlive(buffer) if explicit intent is retained). In
internal/sandbox/windows_identity_windows.go:202-204, :239, and :262, remove the
defer closures referencing info or entry, or replace them with defer
runtime.KeepAlive(&info) / defer runtime.KeepAlive(&entry) respectively.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c2343104-e3d2-400c-8739-a6f655821fe1
📒 Files selected for processing (6)
internal/sandbox/windows_acl_apply_windows.gointernal/sandbox/windows_identity_acl.gointernal/sandbox/windows_identity_acl_test.gointernal/sandbox/windows_identity_logon_windows.gointernal/sandbox/windows_identity_windows.gointernal/sandbox/windows_identity_windows_test.go
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
internal/sandbox/windows_command_runner_windows.go (2)
84-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGive the operator an exit when the principal backend breaks.
This is the one path that hard-fails instead of falling back, and the message is a bare wrapped error. Since the whole feature is opt-in, tell the user how to opt back out — the
ensureWindowsUnelevatedSetupmessage at Line 136 is a good model for actionable runner errors.♻️ Suggested wording
principalToken, ok, err := windowsSandboxPrincipalToken(config) if err != nil { - fmt.Fprintln(stderr, WindowsSandboxCommandRunnerName+": "+err.Error()) + fmt.Fprintf(stderr, "%s: sandbox principal is provisioned but unusable: %v — "+ + "re-run `zero sandbox setup` from an elevated terminal, or unset %s to fall back to the restricted-token sandbox\n", + WindowsSandboxCommandRunnerName, err, windowsSandboxIdentityEnv) return 1 }🤖 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_command_runner_windows.go` around lines 84 - 88, Update the error handling around windowsSandboxPrincipalToken so the stderr message explains that the Windows sandbox principal backend failed and gives the operator an actionable way to disable or opt out of the opt-in feature, following the guidance style used by ensureWindowsUnelevatedSetup. Preserve the existing immediate exit with status 1.
89-97: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHoist the principal lookup above the restricted-token SID computation.
capabilitySIDs,offlineSID,tokenSIDs, andwriteRestrictedare all computed unconditionally and discarded on the principal path. Moving thewindowsSandboxPrincipalTokencall to just after the network-policy validation makes the two backends read as a clean either/or and avoids the wasted SID resolution. (Only do this if the network-enforcement question above resolves in favor of keeping the principal path independent of those SIDs.)🤖 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_command_runner_windows.go` around lines 89 - 97, Move the windowsSandboxPrincipalToken lookup and its success-path handling to immediately after network-policy validation, before computing capabilitySIDs, offlineSID, tokenSIDs, or writeRestricted. Keep the principal-token execution via runWindowsCommandAsUser unchanged, and ensure the restricted-token SID calculations run only on the fallback path.internal/sandbox/windows_identity_secret_windows.go (1)
139-166: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueConsider DPAPI for the on-disk secret. The ACL blocks other users, but the password is still stored in plaintext. If you want defense in depth against offline inspection or backup exposure, encrypt it with DPAPI before writing it.
🤖 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_identity_secret_windows.go` around lines 139 - 166, Update writeWindowsSandboxSecret to protect the password with Windows DPAPI before persisting it, writing the encrypted bytes instead of plaintext while preserving the existing owner ACL and cleanup behavior. Reuse the repository’s existing DPAPI encryption helper if available; otherwise add the minimal Windows-specific encryption step and report encryption failures without writing the secret.
🤖 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.
Inline comments:
In `@internal/sandbox/windows_command_runner_windows.go`:
- Around line 78-97: Update the principal execution branch in the Windows
command runner so deny-mode commands cannot bypass network isolation: either
make the WFP filter use the provisioned principal SID, or bypass the principal
path and continue through the restricted-token backend when NetworkDeny is
enabled. Ensure the existing windowsRuntimeTokenSIDs-based deny behavior remains
enforced.
In `@internal/sandbox/windows_identity_runtime_windows.go`:
- Around line 106-127: Update provisionWindowsSandboxPrincipalForSetup to reset
the password for existing principals before writeWindowsSandboxSecret persists
the credential. Reuse ensureWindowsSandboxUser’s existing account-handling
behavior or adjust the provisioning flow so nerrUserExists accounts receive the
newly generated password, while preserving fresh-account provisioning and
subsequent logon-rights setup.
In `@internal/sandbox/windows_identity_secret_windows_test.go`:
- Around line 181-196: Update windowsSecretACEList to inspect the generic
ACE_HEADER returned by GetAce before interpreting it as ACCESS_ALLOWED_ACE.
Accept only the supported allow-ACE type, and return a clear error for deny,
object, or any other unsupported ACE type so invalid SID offsets cannot be
decoded as trustees.
---
Nitpick comments:
In `@internal/sandbox/windows_command_runner_windows.go`:
- Around line 84-88: Update the error handling around
windowsSandboxPrincipalToken so the stderr message explains that the Windows
sandbox principal backend failed and gives the operator an actionable way to
disable or opt out of the opt-in feature, following the guidance style used by
ensureWindowsUnelevatedSetup. Preserve the existing immediate exit with status
1.
- Around line 89-97: Move the windowsSandboxPrincipalToken lookup and its
success-path handling to immediately after network-policy validation, before
computing capabilitySIDs, offlineSID, tokenSIDs, or writeRestricted. Keep the
principal-token execution via runWindowsCommandAsUser unchanged, and ensure the
restricted-token SID calculations run only on the fallback path.
In `@internal/sandbox/windows_identity_secret_windows.go`:
- Around line 139-166: Update writeWindowsSandboxSecret to protect the password
with Windows DPAPI before persisting it, writing the encrypted bytes instead of
plaintext while preserving the existing owner ACL and cleanup behavior. Reuse
the repository’s existing DPAPI encryption helper if available; otherwise add
the minimal Windows-specific encryption step and report encryption failures
without writing the secret.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 90fab087-5f05-4a9a-ae92-73e983828792
📒 Files selected for processing (4)
internal/sandbox/windows_command_runner_windows.gointernal/sandbox/windows_identity_runtime_windows.gointernal/sandbox/windows_identity_secret_windows.gointernal/sandbox/windows_identity_secret_windows_test.go
|
Validation update: the provisioning chain has now been run for real, elevated, on Windows 11. and the objects it created were really there, confirmed independently afterwards: Verified end to end: NetLocalGroupAdd, NetUserAdd, NetLocalGroupAddMembers and the SID lookup all succeed against the real APIs; a second provision returns the same username and SID, so the idempotent "already exists" handling is correct; and lookup finds what provisioning created. Notably there was no ERROR_PASSWORD_RESTRICTION, so the generated password satisfies the default complexity policy. That also means the hand-rolled USER_INFO_1, LOCALGROUP_INFO_1 and LOCALGROUP_MEMBERS_INFO_3 layouts marshal correctly, which matters because they are passed as raw buffers where a wrong field order fails or corrupts memory rather than erroring cleanly. Still not verified: that test exercises provisionWindowsSandboxIdentity only. LsaAddAccountRights (the batch-logon grant and the deny-interactive hardening) and LogonUser (minting the token) have still never executed, so the identity is proven to exist but not yet proven usable. CI cannot cover either, since it runs unelevated. Also still open: the provisioning entry points have no non-test callers yet. Keeping this a draft until the logon half is exercised too. |
|
Setup is wired now, so the feature is reachable end to end rather than inert.
Provisioning is folded into setup's existing rollback rather than each later failure path having to remember it, and the rollback revokes ACEs before deleting the account. Doing it the other way round would leave ACEs naming a SID that no longer resolves, which is the orphaned residue this model exists to avoid. Everything stays behind How to exercise it, on a machine where creating local accounts is acceptable: Validation status: provisioning (group, account, membership, SID, idempotency) is confirmed working elevated on Windows 11. The logon half now has a test, TestGrantLogonRightsAndMintPrincipalToken, which exercises LsaAddAccountRights and LogonUser and asserts the minted token's user SID is the principal rather than the caller. It has not been run yet; Smart App Control blocks freshly built unsigned binaries on the machine available to me, so it needs a box without that restriction. That is the last unproven primitive and the reason this is still a draft. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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.
Inline comments:
In `@internal/sandbox/windows_identity_runtime_windows_test.go`:
- Around line 11-29: Make TestWindowsSandboxIdentityGating hermetic by clearing
windowsSandboxIdentityEnv from the process environment before running the table,
so the "absent" case cannot fall back to an externally set value. Restore the
original environment after the test using the standard test cleanup mechanism.
In `@internal/sandbox/windows_setup_windows.go`:
- Around line 38-64: Add coverage in the Windows sandbox setup tests for the
flow around runWindowsSandboxSetup: verify opt-out does not call
setupWindowsSandboxPrincipal, and verify an opt-in principal-setup failure still
invokes the existing ACL rollback. Use the test’s existing configuration and
rollback helpers, preserving current success and error behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: bb64b652-8bb9-4259-8b0e-53533dd380cf
📒 Files selected for processing (3)
internal/sandbox/windows_identity_runtime_windows.gointernal/sandbox/windows_identity_runtime_windows_test.gointernal/sandbox/windows_setup_windows.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/sandbox/windows_identity_runtime_windows.go
|
Thanks, this was a useful pass. Went through all three. Network enforcement (the hedge on the second point) turned out to be the real finding. Chasing it down: Fixed in fb8e39b: the principal stands down whenever the network is denied and the restricted-token path runs instead. Keying the filters to the principal's own SID is the follow-up that lifts the restriction, and I would rather do that with the privileged paths validated on a clean box than bolt it on here. Worth flagging that my first regression test for this was worthless. It called Actionable error: taken. The message now names DPAPI: also taken, in deb3a98. The ACL is still the primary control and the thing that keeps the principal from reading its own credential, but you are right that it only binds while the filesystem is the one being asked, so a backup or a mounted image gives up the password in the clear. Hoisting the lookup above the SID computation: leaving it. Now that the principal path is gated on network mode, it is no longer independent of those SIDs, so the ordering earns its keep. Still unproven and called out in the description: |
gnanam1990
left a comment
There was a problem hiding this comment.
Verdict
Changes requested.
Two things drive that. The lookup path below discards a check you deliberately wrote, and it should be fixed regardless of what else happens. Separately, the privileged half of this change has never been executed by anyone, and account provisioning, logon-rights assignment and credential storage are not things I am willing to approve unrun, however sound the design reasoning is. Neither point is a criticism of the direction, which I think is right.
The design reasoning here is unusually clear, and the honesty about what has and has not been run is appreciated.
One practical note before anything else: the description opens by calling this a draft, but the pull request is not marked as a draft on GitHub, so it currently sits open for review and merge. Converting it would match your stated intent. Related, the Smoke jobs for macOS, Ubuntu and Windows, along with Zero Review, were still pending when I looked, so the CI signal you describe as the check for the wiring commit has not yet reported.
What I was able to verify. On macOS, make fmt-check, go build ./... and go vet ./... are clean, and the full suite passes at 82 packages with no failures. More usefully for a change of this shape, GOOS=windows go vet ./internal/sandbox/... exits cleanly and GOOS=windows go test -c compiles the test binary, which type-checks the roughly 1,500 lines of _windows.go that never compile on a non-Windows host. That is not execution, but it does confirm the Win32 call sites, struct definitions and build tags hold together across the whole addition.
I also mutated the ACL ordering to check the test does real work: reversing the entry order returned by buildWindowsPrincipalACLPlan fails TestPrincipalACLPlanEmitsDeniesBeforeAllows. The deny-before-allow invariant is genuinely asserted rather than only documented.
Two further things came back clean and are worth recording. Password generation draws 24 bytes from crypto/rand and encodes them with unpadded base32, giving roughly 120 bits with no modulo bias, and the fixed prefix covering the complexity classes is a reasonable approach. Account naming leaves 11 hex characters of the SHA-256 digest after the nine-character prefix, so 44 bits, which puts a birthday collision far beyond any plausible number of workspaces on one machine.
One substantive finding. lookupWindowsSandboxIdentity (internal/sandbox/windows_identity_windows.go:338-345) collapses every error from resolveWindowsSandboxSID into errWindowsSandboxIdentityUnavailable, which discards the deliberate check you wrote at lines 274-276 refusing a name that resolves to a non-user account.
The effect is that if zero-sbx-<hash> is squatted by a pre-existing local group or alias, resolveWindowsSandboxSID correctly refuses it, but the caller reads that refusal as "not provisioned" and windowsSandboxPrincipalToken (lines 73-76 of windows_identity_runtime_windows.go) falls back quietly to the restricted token. Your own description draws the line in the right place, that only a provisioned-but-unusable identity should surface an error, and this is precisely that case reaching the operator as silence. Distinguishing ERROR_NONE_MAPPED from other lookup failures would preserve the fallback for the common "setup has not run" case while surfacing the rest.
A smaller one: the comment at windows_identity_windows.go:122 refers the reader to sandboxRuntimeKey for how the workspace key is hashed, but no such symbol exists. The function is windowsSandboxWorkspaceKey in windows_identity_runtime_windows.go:44.
On the question you raised for decision. Creating real local accounts being visible to endpoint protection, enterprise policy and net user seems worth settling before this leaves draft, and I agree it is a product call rather than a design flaw. The inversion argument is persuasive on its merits: unreachable by construction is a stronger boundary than an enumerated deny list, and the trustee-keyed revocation answers a real gap.
Limitations of this review. I have no Windows host and no elevated session, so NetUserAdd, LsaAddAccountRights, NetUserDel and LogonUser are unexecuted by me as well. I did not check the raw Win32 struct layouts against the SDK, and I did not review the LSA byte-versus-rune length handling beyond confirming it compiles. Everything above rests on reading the code and on cross-compilation.
Worth flagging for coordination: this addresses the same credentialDenyReadPaths weakness on Windows that I raised on #801, where removing the sandbox HOME and XDG_CONFIG_HOME overrides makes real credential locations the resolution target. The two changes point at the same boundary from opposite sides and would benefit from being sequenced deliberately.
Merge is kevin's call per the program gate.
|
CI is green now. The Windows smoke failure was not from this branch, and it is worth saying what it actually was rather than just re-running until it passed. Three tests failed, all in Fixes are up separately rather than folded in here, since they have nothing to do with the sandbox work and one of them touches product code:
I also opened #811 for something that fell out of the reproduction and is a genuine user-facing bug rather than a test problem: the provider-command timeout is a floor, not a bound. Process creation happens before the timer is armed and the drain after Nothing on this branch changed for any of that. Once #809 and #810 land I will rebase this one. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (3)
internal/sandbox/windows_identity_runtime_windows_test.go (1)
11-22: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTable is still not hermetic.
The
"absent"case falls through toos.Getenv, so this test fails on any machine that actually hasZERO_WINDOWS_SANDBOX_IDENTITY=1exported — precisely the machines doing the elevated validation runs for this PR. Addt.Setenv(windowsSandboxIdentityEnv, "")before the table.🤖 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_identity_runtime_windows_test.go` around lines 11 - 22, Make TestWindowsSandboxIdentityGating hermetic by setting windowsSandboxIdentityEnv to an empty value with t.Setenv before iterating over the test cases, ensuring the "absent" case cannot inherit the host environment.internal/sandbox/windows_identity_secret_windows_test.go (1)
183-198: 🎯 Functional Correctness | 🟡 Minor | 💤 Low valueStill assumes every ACE is an
ACCESS_ALLOWED_ACE.
GetAcereturns a genericACE_HEADER; a deny or object ACE would put the SID at a different offset and this helper would decode garbage, making the "unexpected trustee" assertion misleading rather than failing cleanly. Gate onace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPEand return an error.🤖 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_identity_secret_windows_test.go` around lines 183 - 198, The windowsSecretACEList helper must validate each ACE type before interpreting its SID layout. After GetAce returns, check ace.Header.AceType and return an error for any type other than windows.ACCESS_ALLOWED_ACE_TYPE; only then cast to ACCESS_ALLOWED_ACE and copy the SID.internal/sandbox/windows_identity_acl.go (1)
85-92: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winPath traversal via
ProtectedMetadataNamesstill unaddressed.
filepath.Join(cleaned, name)accepts../separator-bearing values, so a malformedProtectedMetadataNamesentry can materialize a deny ACE outsideroot.Root. This was flagged in a prior review and is still present with no validation added.🔒 Proposed fix
for _, name := range root.ProtectedMetadataNames { + if name == "" || name == "." || name == ".." || filepath.Base(name) != name { + return WindowsACLPlan{}, fmt.Errorf( + "windows principal ACL plan: invalid protected metadata name %q", name, + ) + } entries = append(entries, WindowsACLEntry{ Action: WindowsACLDenyWrite, Path: filepath.Join(cleaned, name),Add a regression test in
windows_identity_acl_test.gocovering a traversal/separator-bearing name once this validation lands. As per coding guidelines,**/*_test.go: "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_identity_acl.go` around lines 85 - 92, Validate each entry from root.ProtectedMetadataNames before constructing the WindowsACLEntry, rejecting traversal or separator-bearing names that could escape cleaned/root.Root; only append entries for safe metadata names. Add a regression test in windows_identity_acl_test.go covering both traversal and separator-bearing input.Source: Coding guidelines
🧹 Nitpick comments (1)
internal/sandbox/windows_identity_windows.go (1)
196-205: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
runtime.KeepAliveinstead of a deferred no-op.
defer func() { _ = info }()does keepinfoalive (the closure captures it), but it reads as dead code and a future cleanup will delete it, silently reintroducing a use-after-free window. The same pattern repeats at Lines 239 and 262.♻️ Proposed change
status, _, _ := procNetLocalGroupAdd.Call( 0, // local machine 1, // level: LOCALGROUP_INFO_1 uintptr(unsafe.Pointer(&info)), 0, ) - // Keep info alive across the call: the struct holds pointers into Go memory - // that the syscall dereferences. - defer func() { _ = info }() + // Keep info (and the Go strings it points at) alive across the call. + runtime.KeepAlive(info) return netAPIStatus("NetLocalGroupAdd", status, nerrGroupExists, errorAliasExists)🤖 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_identity_windows.go` around lines 196 - 205, Replace the deferred no-op keeping info alive in the NetLocalGroupAdd call with runtime.KeepAlive(info) after the syscall returns. Apply the same change to the corresponding patterns around the related calls at Lines 239 and 262, and add the runtime import if needed.
🤖 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.
Inline comments:
In `@internal/sandbox/windows_identity_logon_windows.go`:
- Around line 108-154: The native Windows calls need explicit GC liveness
guarantees for all borrowed arguments. In grantWindowsSandboxLogonRights, add
runtime.KeepAlive for attributes after procLsaOpenPolicy.Call and for entry
after procLsaAddAccountRights.Call, while retaining the buffer keep-alive; also
update the LogonUserW call site to keep the user, domain, and secret pointers
alive after the call returns.
In `@internal/sandbox/windows_identity_runtime_windows.go`:
- Around line 139-145: Update the Windows sandbox identity flow around
ensureWindowsSandboxUser and writeWindowsSandboxSecret so a pre-existing
account’s password is actually synchronized before writing the secret. Remove
the inaccurate claim that the caller resets the password, and ensure the stored
secret matches the account password for both new and existing users.
In `@internal/sandbox/windows_identity_secret_windows.go`:
- Around line 186-196: Update readWindowsSandboxSecret to map permission-denied
errors, including Windows ERROR_ACCESS_DENIED, to
errWindowsSandboxIdentityUnavailable alongside missing-file errors so callers
fall back to the restricted token. Update removeWindowsSandboxSecret to treat
the same unreadable or inaccessible-secret condition as non-fatal, allowing
principal cleanup to continue while preserving other error propagation.
In `@internal/sandbox/windows_identity_windows.go`:
- Around line 213-241: The existing-user path in ensureWindowsSandboxUser must
reset the account password via NetUserSetInfo at level 1003 using USER_INFO_1003
before returning success; update internal/sandbox/windows_identity_windows.go
lines 213-241 accordingly while preserving normal creation behavior. In
internal/sandbox/windows_identity_runtime_windows.go lines 139-145, revise the
related comment to accurately describe that ensureWindowsSandboxUser performs
the password reset.
---
Duplicate comments:
In `@internal/sandbox/windows_identity_acl.go`:
- Around line 85-92: Validate each entry from root.ProtectedMetadataNames before
constructing the WindowsACLEntry, rejecting traversal or separator-bearing names
that could escape cleaned/root.Root; only append entries for safe metadata
names. Add a regression test in windows_identity_acl_test.go covering both
traversal and separator-bearing input.
In `@internal/sandbox/windows_identity_runtime_windows_test.go`:
- Around line 11-22: Make TestWindowsSandboxIdentityGating hermetic by setting
windowsSandboxIdentityEnv to an empty value with t.Setenv before iterating over
the test cases, ensuring the "absent" case cannot inherit the host environment.
In `@internal/sandbox/windows_identity_secret_windows_test.go`:
- Around line 183-198: The windowsSecretACEList helper must validate each ACE
type before interpreting its SID layout. After GetAce returns, check
ace.Header.AceType and return an error for any type other than
windows.ACCESS_ALLOWED_ACE_TYPE; only then cast to ACCESS_ALLOWED_ACE and copy
the SID.
---
Nitpick comments:
In `@internal/sandbox/windows_identity_windows.go`:
- Around line 196-205: Replace the deferred no-op keeping info alive in the
NetLocalGroupAdd call with runtime.KeepAlive(info) after the syscall returns.
Apply the same change to the corresponding patterns around the related calls at
Lines 239 and 262, and add the runtime import if needed.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4be32672-966b-47b1-955b-a7e02d7e5891
📒 Files selected for processing (13)
internal/sandbox/windows_acl_apply_windows.gointernal/sandbox/windows_command_runner_windows.gointernal/sandbox/windows_identity_acl.gointernal/sandbox/windows_identity_acl_test.gointernal/sandbox/windows_identity_dpapi_windows.gointernal/sandbox/windows_identity_logon_windows.gointernal/sandbox/windows_identity_runtime_windows.gointernal/sandbox/windows_identity_runtime_windows_test.gointernal/sandbox/windows_identity_secret_windows.gointernal/sandbox/windows_identity_secret_windows_test.gointernal/sandbox/windows_identity_windows.gointernal/sandbox/windows_identity_windows_test.gointernal/sandbox/windows_setup_windows.go
|
Thanks, this is a good review, and the lookup finding is right. The squatted-name case. Fixed in 9e1e651. You are right that it lands exactly where the description says the line should sit, and I had written the check and then thrown it away one call later. It was worse than the one site you found: The decision sits in its own function rather than inline, because the lookup derives its account name from a workspace key, so a test cannot hand it a name that resolves to a group. The test drives that classifier with a real error from a well-known local group, needs no privilege, and I checked it fails if the old collapse-everything behaviour is restored: The stale comment. Fixed, it is The draft framing. That was stale and I have rewritten the opening. This is not a draft: it is opt-in behind an environment variable and I would rather it be reviewed than sit hidden. The provisioning half has since been run on a real elevated session, so account and group creation are no longer unexecuted. CI. It has reported since, and is green on all nine checks. Three Windows tests did fail on the first run, none of them in code this branch touches. I reproduced two of them locally under CPU contention on a clean tree, so they were pre-existing flakes rather than anything here; they are fixed in #810 and #809, and #811 covers a genuine product bug that fell out of the reproduction. On sequencing with #801. Agreed, and worth being concrete: these do point at the same boundary from opposite sides. #801 removes the sandbox Also worth flagging for the same reason: this backend currently stands down whenever the network is denied, which is the default. WFP filters key on the offline-marker SID and a The two things you verified that I could not, the cross-compiled vet and |
|
Both taken, and the first one was a real bug rather than a documentation slip. The pre-existing account. You are right, and the effect is worse than the comment being wrong. Fixed in e33dce0. The gated provisioning test now provisions twice and logs on with the password from the second run. That is the only assertion worth having here: a stale password is indistinguishable from a correct one until something actually authenticates with it, so checking that the two runs return the same identity would have passed straight through this bug. The keep-alives. Also taken.
On the |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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.
Inline comments:
In `@internal/sandbox/windows_identity_windows_test.go`:
- Around line 239-246: After provisioning the test principal in the gated
identity test, register a t.Cleanup callback that revokes SeBatchLogonRight and
removes the test principal, ensuring cleanup runs on every subsequent failure
path. Keep the existing grantWindowsSandboxLogonRights and
logonWindowsSandboxPrincipal flow unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d03dfa6a-7671-40c4-b4c8-5d77781ed16c
📒 Files selected for processing (4)
internal/sandbox/windows_identity_logon_windows.gointernal/sandbox/windows_identity_runtime_windows.gointernal/sandbox/windows_identity_windows.gointernal/sandbox/windows_identity_windows_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/sandbox/windows_identity_logon_windows.go
- internal/sandbox/windows_identity_runtime_windows.go
- internal/sandbox/windows_identity_windows.go
|
Taken, and it was pointing at more than the test. You are right that the round trip left residue: it granted a real batch logon right to a real local account and had no cleanup at all, so anyone running the gated suite kept both. That is on me, and it got worse when I added the logon step in the last commit. The part worth flagging is that the same hole was in the production teardown. Fixed in fbe340b:
One thing I did not want to take on trust. Treating "this account holds no rights" as success depends on
|
gnanam1990
left a comment
There was a problem hiding this comment.
Verdict
Approve.
Reviewed at fbe340b3995c, base ac50a5a840d2, re-confirmed against the live head before posting.
I withdraw both findings from my previous review. Each is fixed, and the first is fixed in the way I hoped rather than the cheapest way.
lookupWindowsSandboxIdentity no longer collapses every lookup failure into "not provisioned". classifyWindowsSandboxLookupError (internal/sandbox/windows_identity_windows.go) maps ERROR_NONE_MAPPED to errWindowsSandboxIdentityUnavailable and returns everything else unchanged, so the deliberate refusal in resolveWindowsSandboxSID for a name resolving to a non-user account now reaches the operator instead of degrading quietly to the restricted token. TestLookupWindowsSandboxIdentityRejectsNonUserAccount covers exactly that case. The sandboxRuntimeKey comment now names windowsSandboxWorkspaceKey, which exists.
On the execution question, which was my other reason for requesting changes. The position has changed materially. Account and group provisioning have now been run on a real elevated session, the description says so precisely, and all three Smoke jobs plus Zero Review are passing, including windows-latest. The logon half — LsaAddAccountRights and LogonUser — remains unexecuted, and the description says that too, in those words.
I am approving with that gap open rather than in spite of it, for two reasons. The whole surface is behind ZERO_WINDOWS_SANDBOX_IDENTITY=1 and off by default, so no existing install changes behaviour. And the disclosure is accurate and specific rather than implied, which is the standard the review protocol asks for. An unrun privileged path that nobody reaches without opting in, declared plainly, is a reasonable posture for foundation work.
On the new material in this delta. The DPAPI wrapping is well-judged. CRYPTPROTECT_UI_FORBIDDEN is the right flag for a path that may run without an interactive desktop, the LocalFree of the DPAPI-allocated output is correctly deferred, and the ciphertext is copied out rather than aliased. I checked the one thing that looked like a documentation mismatch and it was not: the comment says the principal name is the entropy, and windowsSandboxSecretEntropy derives it from the secret's own filename, which is the principal name — so read and write agree by construction, as the comment claims.
Resetting the password when the account already exists is a real bug fix rather than a refinement. NetUserAdd leaves an existing account untouched, so without NetUserSetInfo the stored secret would not have been the account's password, and the failure would have surfaced much later as an unexplained logon failure. Revoking logon rights before deleting the principal, and keeping the restricted token when the network is denied, are both correct orderings.
Two smaller things came back clean and are worth recording. Replacing defer func() { _ = info }() with runtime.KeepAlive is the correct idiom — the deferred closure did not reliably keep the pointed-to Go memory alive across the syscall, and KeepAlive does. And the KeepAlive calls were added for name and comment as well, not only the struct.
Verification. On macOS, go build ./..., go vet ./... and gofmt -l are clean and the suite passes. More usefully for this change, GOOS=windows go vet ./internal/sandbox/... exits 0 and GOOS=windows go test -c compiles, which type-checks the entire Windows surface including the new DPAPI file. That is not execution, but it confirms the Win32 call sites, struct definitions and build tags hold together across the whole addition.
Limitations. I have no Windows host and no elevated session. LsaAddAccountRights, LogonUser, CryptProtectData and NetUserSetInfo are unexecuted by me. I did not check the raw struct layouts against the SDK beyond confirming the existing layout tests still pass.
This does not clear CodeRabbit's outstanding review, and #812 is stacked on this branch, so landing order matters.
Merge is kevin's call per the program gate.
|
Both findings are correct. I checked each against the head before agreeing, and neither is a misreading. Fixed in 6ccf4cf. 1, the account takeover. Confirmed. Ownership is now read back from the comment provisioning stamps before anything is touched, and a name held by an account Zero did not create fails with a typed The irony is not lost on me. I added exactly this guard to the deletion path in the follow-up PR after CodeRabbit raised deleting-by-derived-name, and did not think to look at the adoption path, which is the more dangerous of the two. Deleting the wrong account is loud. Resetting its password and quietly running as it is not. 2, the partial-failure residue. Also confirmed, and your description of why is precise: the rollback is only constructed after Provisioning now unwinds what the run actually did, in reverse, on every failure path, tracking the four things you listed. One deliberate difference from your list, worth stating because it is a judgement rather than an oversight. Cleanup is scoped to what THIS run created. An account that already existed and belongs to Zero is a working principal from an earlier setup, so deleting it because a later run failed would turn a partial failure into a total one. For the pre-existing case the repair is dropping the stored secret instead: this run reset the password, so the secret no longer matches, and absent beats stale because the command path treats a missing secret as "not provisioned" and falls back to the restricted token rather than failing. If you think that is the wrong call I will change it. 3, the unexecuted LogonUser path. Agreed, and I have said so in the description since the start rather than being talked into it. It is the central runtime path and it has not run end to end on an elevated machine. Smart App Control on my box blocks freshly built unsigned binaries, which is exactly the class of binary the gated provisioning test produces. I am not going to claim that as verified, and I do not think opt-in gating substitutes for running it. You also asked for a test with an unrelated existing account on the derived name. Added, driven against
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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.
Inline comments:
In `@internal/sandbox/windows_identity_runtime_windows.go`:
- Around line 146-190: Update the provisioning cleanup flow around the undo
closure and grantWindowsSandboxLogonRights call: compute secretPath immediately
after identity provisioning succeeds, before granting logon rights, and remove
the secretWritten condition so undo removes any resolved secret path on
subsequent failure. Preserve the existing no-op behavior when secretPath is
empty and keep successful secret writing unchanged.
In `@internal/sandbox/windows_identity_windows.go`:
- Around line 389-432: Update setupWindowsSandboxPrincipal to remove the
existing Windows sandbox secret when provisioning succeeds in changing or
reusing an account but setup fails before writeWindowsSandboxSecret. Ensure the
rollback error path deletes the stale .secret file, while preserving the normal
secret write and unrelated provisioning error behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 24ed1d1c-eaa0-4d51-843c-1e1a7a825854
📒 Files selected for processing (3)
internal/sandbox/windows_identity_runtime_windows.gointernal/sandbox/windows_identity_windows.gointernal/sandbox/windows_identity_windows_test.go
|
Both findings are the same hole seen from two angles, and you are right: the cleanup I added missed the one window it was written for. Provisioning always sets the account's password, including resetting a pre-existing owned account's, so from the moment it returns the stored secret is already stale. My Fixed in 832f53a: the path is resolved from the account name before anything can fail, and removal is unconditional rather than gated on Worth naming the pattern, since this is twice now on this PR. The takeover fix and this one are both cases where I reasoned correctly about what should happen and then wrote a condition that did not cover the case I was reasoning about. Reading the comment I had written would have told you the intended behaviour; only reading the code shows it did not happen.
|
gnanam1990
left a comment
There was a problem hiding this comment.
Verdict
Approve.
Reviewed at 832f53a98d74, base 5d1869e, re-confirmed against the live head before posting. My earlier approval at fbe340b was dismissed by the push; this replaces it, and the new work is strictly better.
The two commits since then are both real improvements, not polish.
windowsSandboxUserIsManaged closes a hazard that was live in the version I approved. The account name is derived from a workspace hash rather than discovered, so it can be occupied by an account with nothing to do with Zero — and provisioning would previously have adopted it and reset its password. Reading back the comment stamp before adopting, and refusing with a named error otherwise, is the right shape, and the same predicate is reused on the delete path in #812. Dropping the stored secret when provisioning fails closes the matching half: a secret file that no longer corresponds to any account is worse than none, because it looks provisioned.
One substantive finding, non-blocking, on the adoption gate.
provisionWindowsSandboxIdentity proves ownership using the comment field alone. It does not inspect the adopted account's group memberships. An account named zero-sbx-<hash>, carrying Zero's comment, and also a member of Administrators would pass the gate: Zero resets its password, adds it to the sandbox group, and mints principal tokens for it. The sandboxed child then runs as an administrator, which inverts the property this whole design rests on — your description's argument is that a separate account has no access to the caller's profile by construction, and an adopted account with extra memberships is precisely the case where that stops being true by construction.
I want to be fair about reachability: planting such an account requires administrator rights already, so this is not fresh escalation. It is a persistence and laundering path — something that had admin once leaves a stamped account behind, and Zero thereafter grants it sandbox duty on every run — and it is also the shape a botched or partial earlier provisioning could leave behind on its own. Given that the model's selling point is a boundary that holds by construction, asserting the adopted account's memberships (at minimum, that it is not in Administrators) rather than only its comment would make the claim true rather than nearly true. A comment is a stamp, not a capability check.
What I verified. On macOS: gofmt, go build ./..., go vet ./... clean, suite passing. GOOS=windows go vet ./internal/sandbox/... exits 0 and GOOS=windows go test -c compiles, which type-checks the whole Windows surface including the two new netapi32 procs and the USER_INFO_1 read-back. That is type-checking, not execution.
Limitations, unchanged and still the main thing a reader should weigh. I have no Windows host and no elevated session. NetUserGetInfo, NetApiBufferFree, NetUserSetInfo, LsaAddAccountRights and LogonUser are unexecuted by me. Your description remains accurate about which halves you have run, and that accuracy is why I am comfortable approving with the logon path still unrun: the feature is behind ZERO_WINDOWS_SANDBOX_IDENTITY=1 and off by default, so nothing changes for an existing install.
CodeRabbit's changes-requested from 08:17 is still outstanding and is separate from this.
Merge is kevin's call per the program gate.
832f53a to
99fefdc
Compare
anandh8x
left a comment
There was a problem hiding this comment.
Review at 99fefdc
PR #808 — Windows sandbox principals (foundation for #662). 14 files, +2559, 12 commits, all new *_windows.go files (build-constrained) except windows_identity_acl.go which is pure-Go ACL-plan logic that compiles on all platforms. Opt-in behind ZERO_WINDOWS_SANDBOX_IDENTITY=1.
Verdict: approve. The design is sound, the fail-soft contract is right, and the honest caveats are the right ones.
What this does
Gives the sandbox its own identity on Windows: a separate local account per workspace in one managed group. This inverts the read-confinement problem — instead of trying to deny the caller's own account (which locks Zero out too), a separate account has no access to the caller's profile by construction, so credential stores are unreachable without enumerating deny rules.
What's good
- The inversion is the right design. Every other Windows backend derives its token from the calling user via
CreateRestrictedToken, which is whycredentialDenyReadPathsis a no-op on Windows. A separate account makes "what to GRANT" the interesting question instead of "what to DENY," and the same SID keys write grants and firewall rules. - Fail-soft contract is correct. No provisioned account, no stored secret, or opt-in off →
ok=false, nil error, restricted-token backend runs unchanged. Only a provisioned-but-unusable identity surfaces an error (broken sandbox, not absent sandbox). The runner integration (windows_command_runner_windows.go) is a clean 25-line addition that tries the principal first and falls back. - Network-denial tradeoff is honest. A principal token from
LogonUsercan't carry the offline-marker SID that WFP filters key on, so the principal stands down when the network is denied and the restricted-token path runs instead. The PR explicitly says "trading network denial for read confinement would have been the wrong way round." Keying filters to the principal's own SID is the named follow-up. - Provisioning is idempotent. "Already exists" statuses are success. Re-running
zero sandbox setupconverges instead of accumulating accounts. Password is reset on re-provisioning so the stored secret stays in step with the account. - Squat protection.
windowsSandboxUserIsManagedreads back the comment stamp before adopting an existing account. Refuses with a named error (errWindowsSandboxNameCollision) if the name is taken by a non-Zero account. This closes the "reset a stranger's password" hazard. - Secret storage is layered. DACL naming only the invoking user + SYSTEM, applied to an empty file before the password is written (bytes never exist under inherited permissions),
SE_DACL_PROTECTEDso inherited ACEs can't reach it, plus DPAPI (CryptProtectData) encryption with the principal name as entropy so a blob copied to another path fails to decrypt. The testTestStoredSecretDACLNamesOnlyOwnerAndSystemreads the DACL back and fails if any other trustee appears; another assertsSE_DACL_PROTECTED. - ACL plan is deny-before-allow. Carve-outs survive Windows DACL evaluation order. Trustee-keyed revocation drops every ACE naming the principal without needing a record of what was granted — the cleanup path the capability-SID model lacks.
- Rollback is thorough.
provisionWindowsSandboxPrincipalForSetupcomputessecretPathearly (before anything can fail), the undo closure removes the secret unconditionally ("provisioning has already replaced the account's password by the time any of this can fail, so whatever is on disk cannot authenticate"), andsetupWindowsSandboxPrincipalcallsremovePrincipal()on ACL-plan failure, which removes secret → logon rights → account in that order. - Logon rights are least-privilege. Only
SeBatchLogonRightgranted; interactive, network, remote-interactive, and service logon explicitly denied.LogonUserpinned to"."so a same-named domain account is never picked up. - Platform separation is clean.
windows_identity_acl.go(plan logic, no build tag, compiles everywhere, testable on Linux) vs*_windows.go(syscall execution, build-constrained). Cross-compile forGOOS=windowsclean;GOOS=windows go test -ctype-checks the full Windows surface includingnetapi32procs andUSER_INFO_1layout.
Verification performed
GOOS=windows go vet ./internal/sandbox/...— cleanGOOS=windows go test -c— compiles (type-checks all Windows-specific code)go build ./internal/sandbox/...(Linux) — cleango test ./internal/sandbox/(Linux, from non-/tmppath) — pass, all 14 tests greengo vet ./internal/sandbox/...— clean
CodeRabbit's findings are addressed
CodeRabbit's latest CHANGES_REQUESTED (08:17Z) asked for (1) computing secretPath before granting logon rights and removing the secretWritten condition, and (2) removing the stale .secret file when provisioning succeeds but setup fails before writeWindowsSandboxSecret. Both are addressed by commits 99fefdc and 52f843a (pushed 09:46Z, after the review). The undo closure now computes secretPath early and removes it unconditionally; setupWindowsSandboxPrincipal's rollback calls removePrincipal() which removes the secret first.
gnanam's non-blocking finding (acknowledged, not blocking)
gnanam's APPROVED review notes that the adoption gate (windowsSandboxUserIsManaged) checks the comment field alone, not the account's group memberships. An account named zero-sbx-<hash> with Zero's comment but also in Administrators would pass the gate. gnanam correctly frames this as a persistence/laundering path (not fresh escalation, since planting requires admin already). The fix — asserting the adopted account is not in Administrators — is a reasonable follow-up but not a blocker given the opt-in gate and the admin prerequisite for exploitation.
Honest caveats (from the PR description, still accurate)
- The logon half is unproven.
NetUserAdd,LsaAddAccountRights,LogonUserneed elevation; they compile and are layout-checked but haven't run to completion (Smart App Control blocked the test binary). The provisioning round-trip test is gated behindZERO_WINDOWS_IDENTITY_PROVISION_TEST=1plus an elevation check. - Creating real local accounts is user-visible. AV/EDR commonly flag
NetUserAdd; enterprise policy often blocks local account creation; accounts appear innet userand Settings. The opt-in gate makes this a deliberate call.
These are the right caveats for a foundation PR. The feature is off by default; nothing changes for an existing install.
Verdict
Approve. The design inverts the Windows read-confinement problem correctly, the fail-soft contract is sound, the rollback paths are thorough, and the honest caveats are the right ones. gnanam's non-blocking finding (membership check on adoption) is worth a follow-up. CodeRabbit's two actionable findings are addressed by the latest commits. Ready for kevin to merge.
… open the lease relative to it prepareSandboxRuntimeLease created the parent by pathname and opened the lease beside it before ensureRuntimeTreeDirs validated the owned path, so a link or junction planted at the fallback anchor's reusable v1 child sent the .lease into another directory and only then failed validation. The parent is now walked and created without following links, and the lease is opened relative to a no-follow handle on that validated directory, so a component swapped in after the check cannot move the open either. Pinned on both platforms with a redirected v1 and an untouched control.
The materialization record verified the anchor's identity but recorded the created children by name, so after setup created .git/config another process could rename it aside, put an ordinary file at that name beneath the unchanged anchor, and have a later setup failure delete the replacement. Each created directory and the leaf file now carry the identity read from the handle that created them; rollback refuses to descend through a created component that is no longer that object, and the delete disposition is set on a handle whose identity was checked, so nothing renamed in between can be the thing removed.
Preparing the runtime candidates rewrote an existing root's DACL with a protected owner-only descriptor before the ACL transaction had a baseline, so a retry that failed on the second candidate, or in the apply, returned with the earlier setup's capability grant gone while the old marker still claimed success. Setup now snapshots each existing candidate's DACL and identity before preparation and restores it, protection state included, on every failure that follows, and after the transaction's own rollback when a later step fails.
The unelevated command's plan lists both runtime candidates, but nothing on that tier created the one this process did not select, so with a fresh usable cache the runner refused its own plan with "windows ACL target does not exist" and the command never launched, on every retry. The parent now creates the missing candidates before the runner starts, where TEMP is still the operator's, using setup's own ownership and no-follow checks, and leaves an existing candidate as it is so the grant the previous command applied is not stripped and reapplied on every launch. A file or reparse point at a candidate's name is refused by name.
…back's own report
…x regressions run under macOS's /var symlink
|
@jatmn @gnanam1990 Merge with main. #1040 landed while this was open and both branches touch the ACL apply, so the resolution is a policy decision and I want it on the record rather than buried in a merge commit. Main attaches an anchor to every derived carveout and refuses a junction on the derived tail while leaving the operator's own ancestors alone, because a workspace on a junction or a dev drive is a configuration that works. This branch refused any reparse point anywhere on an ACL target's path. The merged apply keeps main's rule: the plan apply opens its target with the final-component check only and relies on Merge readiness, the Windows smoke. Production, in the order of the review.
Tests. The mocked provisioning fixture fakes and records the account deletion now, so the created-principal LSA failure asserts exactly one removal through the fake and the adopted case asserts none; the legacy-comment upgrade is faked there too. The native round-trip test derives its second account's key from a fixture-owned workspace, registers cleanup the moment ownership exists, deletes only what it created, and reports cleanup errors. CI is 12 of 12 at this head, including the descriptor test on the Linux and macOS jobs. Locally: |
|
@coderabbitai approve |
✅ Action performedComments resolved and changes approved. |
gnanam1990
left a comment
There was a problem hiding this comment.
Re-review of head 17f55f4e.
The previous Windows smoke and ambient principal-mode failures are fixed: current CI is green, the focused sandbox/peermsg/CLI/doctor packages pass, and the opt-in transport tests now pass. The other previously reported runtime, rollback, helper-boundary, account-cleanup, and fixture-isolation paths have corresponding fixes and regression coverage.
[P2] Resolve the full inline Git alias chain before allowing repository creation
internal/sandbox/analyzer.go:361
gitSubcommandCreatesRepository returns false once depth >= 4. Git continues resolving longer alias chains, so this still bypasses the nested-repository guard. In an ancestor-governed workspace, the following command is allowed by the current analyzer and Git 2.55.0 creates the local .git directory:
git -c alias.a=b -c alias.b=c -c alias.c=d -c alias.d=e -c alias.e=init a .
A disposable regression test on this head observed action=allow with no block, and the real Git command exited 0 with local_git=yes. That leaves the new repository metadata without the carveouts this guard is meant to preserve.
Please resolve aliases until a terminal subcommand using cycle detection (and fail closed on cycle/depth exhaustion in this nested-workspace guard). Add both a chain longer than four ending in init and a harmless long chain ending in status as controls.
Process gate: the branch is currently three commits behind main; refresh it before the next review per repository policy.
Validation on this head: make fmt-check, go vet ./..., Windows cross-build, focused package tests, and the opt-in transport regression passed. All current GitHub checks, including Windows smoke and race detection, are green. No dependency, vendored-code, submodule, or external-service integration changes were introduced.
…losed when it has none The depth cap gave up with false, so a five-link alias chain ending in init passed the nested-repository guard and git created the repository. The resolver now follows the chain until a terminal subcommand with the visited names kept, and under this guard a cycle, a dangling alias or an empty expansion is a refusal rather than a pass: an alias the analyzer cannot follow to its end is not evidence that nothing gets created. A five-link chain ending in status stays allowed.
|
@gnanam1990 you are right, and it was worse than a short cap: giving up with Main is merged again, three commits including the 0.9.0 release. CI is 12 of 12 at |
gnanam1990
left a comment
There was a problem hiding this comment.
Approved head 378b38c.
The remaining inline-alias blocker is fixed. Alias resolution now follows the chain to a terminal command with cycle detection and fails closed for unresolved/empty cycles under the nested-workspace guard. The regression covers a five-link chain ending in init, plus an equally long harmless chain ending in status; both pass locally.
Prior runtime, rollback, helper-boundary, account-cleanup, fixture-isolation, Windows smoke, and ambient principal-mode findings remain closed on this head.
Validation: targeted alias and transport tests passed; sandbox and peermsg packages passed; formatting, go vet ./..., and the Windows cross-build passed. GitHub reports all 12 checks green, including Linux/macOS/Windows smoke and race detection. The PR is mergeable and current with main. No dependency, vendored-code, submodule, or external-service integration changes were introduced.
No evidence-backed blockers remain in the reviewed scope. Local internal/cli was stopped after 372 seconds without output; the exact-head CI suite completed successfully.
anandh8x
left a comment
There was a problem hiding this comment.
windowsPrincipalLaunchAvailable() currently always returns an error, so principal provisioning remains disabled. Could we complete the launch path with a short-lived trusted runner?
Proposed flow:
- Elevated setup provisions the identities, protected credentials, and ACL/network policy.
- Ordinary unelevated Zero launches a fixed runner under the selected sandbox account using
CreateProcessWithLogonW. - The runner restricts its own token with the required capability SIDs, then launches the command.
- Protected IPC carries requests, input/output, and cancellation, with runner identity verification and credentials kept out of arguments, environment variables, and logs.
This avoids requiring cross-account CreateProcessAsUser privileges in the ordinary parent.
One prerequisite: CreateProcessWithLogonW requires local-logon permission, which conflicts with the current SeDenyInteractiveLogonRight. Please resolve that policy trade-off explicitly; if batch-only logon is mandatory, another authenticated launch mechanism is needed.
Before enabling provisioning, verify native Windows execution from an unelevated caller after elevated setup, including allowed operations, denied private-fixture reads/out-of-scope writes, offline network enforcement, and cancellation cleanup.
Also update the description: it still says network-deny principals are ineligible, while the code now has offline/online roles and a separate launch refusal.
gnanam1990
left a comment
There was a problem hiding this comment.
Re-reviewed exact head 378b38c3634f333993ea5e1778946bef2e28a31a (unchanged since my previous approval). One newly reproduced blocker supersedes that approval.
[P2] Parse alias expansion syntax before classifying repository creation
internal/sandbox/analyzer.go:380-384 uses strings.Fields(expansion) and classifies only fields[0]. Git parses quoting and global options inside an alias expansion, so both of these bypass the nested-workspace creation refusal:
git -c alias.a='-c alias.b=init b' a .
git -c 'alias.a="init"' a .In separate temporary workspaces governed by a real ancestor repository, an exact-head diagnostic drove Engine.Evaluate and then executed the identical argument vector with Git 2.55.0. For BOTH cases: action=allow, Block=nil, Git exited successfully, and the workspace acquired its own .git. The new metadata therefore misses the config/hooks carveouts this guard substitutes for. The five-link alias regression passes but does not cover this parsing boundary.
Please classify the command Git actually executes: tokenize alias syntax with quoting, account for alias-local global options/settings, retain cycle detection, and fail closed when the expansion cannot be classified. Add both demonstrated cases through the nested-workspace gate, with quoted/option-bearing harmless aliases and standalone-workspace controls. This is one parsing-root-cause finding, not another depth-cap change.
Other notes: principal provisioning is intentionally closed by windowsPrincipalLaunchAvailable() at both setup entry points. I am not requiring a trusted launch runner in this foundation PR; enabling that lifecycle needs a separately agreed scope and native Windows proof. However, update the description's stale claims that network-deny principals are ineligible and network-allow commands engage the backend: eligibility now uses the opt-in, offline/online roles exist, and the provisioning entry point refuses all principal setup while launch is unavailable. Keep the foundation/not-a-fix-for-#662 scope explicit. The refreshed main is also one commit ahead (99721c7); synchronize before merge per repository policy.
Validation: sandbox/peermsg packages and affected race checks passed; opt-in caller transport/preflight controls passed; make fmt-check, go vet ./..., and Windows amd64 cross-build passed. Exact-head GitHub CI is green, including native Windows smoke. The two disposable alias regressions failed for the stated bypass; their diagnostic file was removed afterward, leaving a clean checkout. No dependency, vendored-code, submodule, or external-service integration changes were found. No implementation, commit, push, or merge was performed.
…repository guard The guard classified the first whitespace-separated field of an alias value, so an expansion carrying its own -c option (alias.a=-c alias.b=init b) or quotes (alias.a="init") reached init unseen, and both spellings created a repository in a nested workspace. Alias values are now split with the rules of split_cmdline (quotes anywhere in a word, backslash escapes outside single quotes), run through the in-alias option handling git applies (-c and --config-env push definitions the next lookup sees, pager switches are skipped, anything else is fatal in git and is refused here), and followed with per-path cycle detection. Definitions from the environment the call sets (GIT_CONFIG_COUNT with GIT_CONFIG_KEY_n and GIT_CONFIG_VALUE_n, and GIT_CONFIG_PARAMETERS) and from --config-env are read as well; a definition that cannot be read statically refuses. The attached -cNAME=VALUE spelling is no longer recognised: git rejects it as an unknown option and nothing runs. Reported by @gnanam1990.
|
@gnanam1990 at You were right that the resolver stopped at While I was in there, the same command can arrive with the definition moved out of sight, and both of these worked against the old head on git 2.54: Dropped the attached Each hunk is pinned: replacing the tokenizer with The description is rewritten as you both asked: eligibility is the opt-in, the two roles are described, provisioning refusing while @anandh8x thank you for the runner sketch. The logon-right conflict you point at is real, and it is exactly why that path needs its own design rather than a patch here. As gnanam says, this PR is the foundation and refuses to provision until a launch path exists, so the trusted runner, its IPC and the native proof from an unelevated caller belong to a separate PR with its own scope. If the description now says that clearly enough, I would be grateful for a re-review; if you want the runner inside this PR regardless, say so and I will put the scope question to kevin rather than argue it here. |
jatmn
left a comment
There was a problem hiding this comment.
I found issues that need to be addressed before this is ready.
Merge readiness
- All required GitHub checks on head
df9989ebare passing (including Windows smoke). Branch is current withmain(merge-base equals live target99721c76). No merge conflicts reported. - Review used a local
git difffor the full patch becausegh pr diffexceeds GitHub’s 20k-line API limit; metadata and checks were taken from live GitHub.
Findings
-
[P1] Ancestor-governed nested workspaces: repository-creation guard is incomplete on PR-changed entry paths
Attribution: PR-introduced / PR-activated. Merge-base always materialized.git/configand.git/hookscarveouts and had nonested_git_initengine block; this PR removes carveouts when an ancestor owns git metadata and compensates only throughEngine.Evaluateplus git-oriented static analysis.
Stated contract: PR body — "in a workspace governed by an ancestor repository … a command that would create a repository there is refused with an explanation";ReasonNestedGitInit— "Every git init in the command is refused" (same family of guarantees for repo creation in governed nested workspaces).
Root cause: the nested-repository rule is enforced only insideEngine.Evaluateand only whenanalysis.GitInitis set (git init/clone/init-db and alias-resolved equivalents). Carveouts are deliberately omitted on these workspaces, so any path that skipsEvaluateor does not classify repo creation leaves the workspace write grant able to create an unprotected.gittree (writable config/hooks; no Windows deny-delete plan until setup is re-run for a new tree).
What fails:- In an ancestor-governed nested workspace,
zero sandbox exec -- git init(orgit clone …) runs becauserunSandboxExeccallsBuildCommandPlanonly and neverEvaluate, while agent shell tools callEvaluatefirst (internal/tools/registry.go). The new CLI is documented as exercising the real sandbox the same way tool execution does (internal/cli/sandbox_exec.go), but it omits the decision layerzero sandbox checkalready uses. - The same workspace allows
mkdir .git/ equivalent non-gitshell creation:risk.goaddsnested_git_initonly whenanalysis.GitInitis true, thenEvaluateauto-allows ordinary shell when the sandbox is active (engine.go~425–430). Tests covergitspellings (git_nested_init_refusal_test.go), not shell-created metadata.
In this PR (must close together): internal/cli/sandbox_exec.go— noEvaluatebeforeBuildCommandPlaninternal/cli/sandbox.gohelp text implying exec matches production tool gatinginternal/sandbox/risk.go/internal/sandbox/analyzer.go— repo creation signal limited to git builtins/aliasesinternal/sandbox/profile.go— nil git carveouts whengitMetadataGovernedByAncestor(depends on guard above)- Tests: add exec + nested-workspace cases; add non-git repo-creation refusal (or explicitly narrow PR copy if product chooses not to block)
Unchanged on main (do not edit in this PR): unrelated principal/launch-seam work.
Required correction: beforeBuildCommandPlanfromsandbox exec, run the sameEngine.Evaluategate production shell tools use (deny/prompt/allow semantics aligned withregistry.go), or extract one shared helper both call. Extend the nested-repo risk classifier to cover non-gitcreation of.gitmetadata in ancestor-governed workspaces (or update every in-diff operator surface that claims commands “that would create a repository” are refused). Add tests provingzero sandbox execcannot rungit init/git clonein governed nested workspaces and that shellmkdir .git(or equivalent) is blocked or documented.
Author fix: close the Root cause on every “In this PR” row in one pass — wire exec throughEvaluate, broaden or honestly narrow the repo-creation contract, and add the missing tests; do not patch onlysandbox_exec.gowithout fixing analyzer/risk/help copy.
Out of scope: Windows principal launch broker, reverting carveout omission without a replacement guard, rewriting runtime cleanup leases on main.
- In an ancestor-governed nested workspace,
-
[P2]
git clonein a governed nested workspace surfaces the network block before the nested-repository refusal
Attribution: PR-introduced. Merge-base had nonested_git_initbranch; this PR inserts it immediately after the existing network gate inEvaluate.
Stated contract:git_nested_init_refusal_test.go— clone refusal is "a separate decision from the network prompt and has to stand on its own"; operator text inReasonNestedGitInitis distinct fromReasonNetworkBlocked.
Root cause:Evaluatechecksnetworkrisk (prompt/deny under defaultNetworkDeny) beforeHasRiskCategory(risk, "nested_git_init"), sogit clonein a governed nested workspace hitsBlockNetwork/ network prompt first even though carveouts are absent and repo creation is the primary hazard.
What fails: operators see network remediation instead ofReasonNestedGitInitunder default policy; tests only assertBlockNestedGitInitfor clone whenpolicy.Network = NetworkAllow(TestNestedWorkspaceRefusesGitCloneIntoTheRoot).
In this PR (must close together):internal/sandbox/engine.go— decision orderinginternal/sandbox/git_nested_init_refusal_test.go— addNetworkDeny+ clone case expectingBlockNestedGitInit(or shared reason) before or instead of network prompt
Unchanged on main: network policy defaults.
Required correction: when bothnested_git_initandnetworkapply, return the nested-repository denial (or evaluatenested_git_initbefore the network gate for repository-creating git commands). Add a test with defaultNetworkDenyproving the nested-repo block/reason is what the operator sees forgit clonein a governed workspace.
Author fix: fix ordering and add the missing test in the same change; do not only adjust test expectations.
Out of scope: changing global network approval policy.
…nested clone as nested Two findings from jatmn on the nested-repository guard. `zero sandbox exec` is documented as taking the path a shell tool takes. A shell tool is evaluated by the engine and then planned; this went straight to BuildCommandPlan, so nothing that lives in Evaluate applied. In a workspace governed by an ancestor repository that is the nested-repository guard, which is the only thing standing in for the git carveouts setup deliberately does not plan there, and `zero sandbox exec -- git init` created the repository with a writable config and hooks. The command now asks the engine first, with the argv rendered as command text that keeps one argument one word, and a denial is a denial. Running it from a terminal counts as the approval a session prompts for and lifts only what that approval lifts. `git clone` is both a network command and a repository-creating one, and the network gate ran first. Under the default NetworkDeny a clone in a governed workspace came back as a network prompt, asking for an approval that could never make the command runnable, and the reason that decides it was never shown. The nested-repository refusal does not depend on policy, permission or mode, so it now comes first. The rule's limit is written down where the rule is. It refuses git creating a repository. It is not containment of the .git pathname: a repository assembled with mkdir and a few writes, an archive or a script is not recognised, and no static reading of a shell command can recognise all of them. A test pins that limit so it is not read as coverage.
|
@jatmn the P2 and the first half of the P1 are fixed in
A nested clone is refused as nested. The refusal now comes before the network gate, since it is the one no approval can lift. The hand-assembled repository. You are right that I do not think a classifier closes it. The real fix is to have the carveouts back for a governed workspace, which reverses The decision. Either (a) plan the config and hooks carveouts for a governed workspace again, accept the empty control directory on Windows and bubblewrap, and keep the git guard as the thing that explains itself; or (b) keep this design and accept the exposure above, documented. I recommend (a) and can have it up quickly. I did not want to reverse a change you asked for without asking. CI 12 of 12 at |
…pository This reverses 26958ac on measurement rather than on argument. That commit skipped the config and hooks carveouts when an ancestor owned the git metadata, so Zero would not create a control directory competing with the ancestor's for git's discovery walk. The consequence it named does not reproduce: a .git holding only config and hooks is not a valid repository, so rev-parse still answers with the ancestor, status still works, and a core.fsmonitor written into that config is never executed. A new test drives real git and fails if a future git changes that. What the skip cost is much larger. With no carveout on the root nothing denied writes to <root>/.git at all, so a sandboxed command could assemble a repository there by hand, with mkdir and a few file writes and not one git command among them, and put core.fsmonitor in its config. Zero runs git -C <workspace> status outside the sandbox from three places, and git executes it. Main does not have that exposure, because main plans the carveouts here. The nested-repository refusal stays. It recognises git creating a repository and cannot recognise mkdir, so it is the layer that explains itself to an operator rather than the boundary. The boundary is the deny ACE, back where it can be enforced at write time. The setup guard in the refusal test now asserts the opposite of what it did: it requires config and hooks to be denied, and fails if they disappear again.
|
@jatmn thanks for the approval, and sorry: I have just dismissed it, along with @gnanam1990's and @anandh8x's review requests, by pushing I asked a question in my last comment and read the The consequence that commit named does not reproduce. A What the skip cost is bigger. With no carveout on that root, nothing denied writes to So the boundary is back where it can be enforced at write time. The nested-repository refusal stays exactly as it is, but as the layer that explains itself to an operator, not as the thing holding the line: it recognises git creating a repository and it cannot recognise The setup guard in If you still prefer the other side of this,
|
jatmn
left a comment
There was a problem hiding this comment.
approving with current head.
euxaristia
left a comment
There was a problem hiding this comment.
This is the strongest security change in the queue and the gate discipline is real: windowsPrincipalLaunchAvailable returns unavailable unconditionally today, so no principal runs a command until maintainers make the policy call. Provisioning details are right: offline and online accounts with ownership-comment verification and privileged-group (SID-resolved) adoption refusal, crypto-random passwords never in argv and sealed under a handle-DACL before the bytes exist plus DPAPI, LogonUser pinned to the local machine with only batch logon granted, and post-mint re-checks for squatted names and elevation into Administrators. The deny-probe set (DACL trustee read-back, deny-before-allow ordering, jail-SID exclusion, DPAPI non-transfer) is genuine. Three things to resolve before the launch path lands: two behavior changes ship ungated to every install (the DELETE right on the write ACL with the shared deny-delete guard on .git, and the nested-repository git guard) plus a marker schema bump forcing re-setup; the runtime-root contract here is superseded by #901's recorded-root approach so this needs a rebase onto #901; and the end-to-end logon half has never run elevated on a clean box, while the real-local-accounts-visible-to-EDR question deserves an explicit maintainer decision.
anandh8x
left a comment
There was a problem hiding this comment.
Approving the current head. My earlier requests are resolved — the launch path is gated off unconditionally rather than shipped half-enabled, and the description now states plainly that this is a foundation for #662, not its fix.
The ungated changes (nested-repository git refusal, .git deny-delete, DELETE on the write ACL, marker bump) are the right calls as written and are documented in the description; flagging them for release notes as euxaristia noted makes sense.
Opt-in behind
ZERO_WINDOWS_SANDBOX_IDENTITY=1. Provisioning was exercised on a real elevated session before the launch gate landed; with the gate in place, setup refuses to provision a principal until a launch path exists, so today the opt-in changes whatzero doctorreports and nothing about how commands run. Both halves are described below.What this does NOT do yet
Three corrections to how earlier versions of this description read, all raised in review.
This is not a fix for issue 662, and no principal runs a command today. Eligibility for the principal backend is the opt-in and nothing else (
windowsSandboxPrincipalEligible); network mode no longer decides it. What stops the backend from engaging is the launch path: an ordinary command process cannot obtain a token for another account, elevated setup cannot hand it that authority, and no bootstrap or broker exists yet to carry it across.windowsPrincipalLaunchAvailableanswers exactly that, and it answers "unavailable" on every machine, so both setup entry points refuse to provision a principal (refusing to provision a sandbox principal: ...) and every command keeps running on the restricted same-user token.credentialDenyReadPathstherefore remains a no-op on Windows. This PR is the foundation for issue 662, not its fix; the trusted launch path is its own piece of work with its own scope and its own native proof, and it is not in this PR.Network denial for a principal is a role, not a reason to stand down. There are two principals per workspace,
offlineandonline, differing only in membership of the group the WFP block filters key to, andwindowsSandboxRoleForNetworkmaps anything that is not an explicit network allow ontooffline. An earlier version of this PR disabled the backend whenever the network was denied; that restriction is gone, and the role is what carries the network decision once a launch path exists.Two changes here are not gated by the opt-in.
WindowsACLAllowWritenow includesDELETE.FILE_DELETE_CHILDis deliberately NOT granted: it would let a sandboxed command delete a protected carveout such as.git/configthrough its parent directory and recreate it without the deny ACE. That mask is shared with the capability-SID plans, so it applies on every elevated setup re-run whether or not the env var is set. It is a fix rather than a regression (without it a sandboxed command could create files it could never delete or rename), but it is a real behaviour change for installs that never opt in, and it belongs in the release notes rather than buried in a principal PR. The nested-repository guard below is the other one.Why
credentialDenyReadPathsopens withif runtime.GOOS == "windows" { return nil }, so on Windows no credential path is protected (#662, and the Windows half of #675). That is not an oversight and not a one-line fix.Every Windows backend derives its token from the CALLING user via
CreateRestrictedToken. A deny-read ACE that would stop the sandboxed child reading~/.awsnames the same account Zero itself runs as, so it would lock Zero out too. The one existing escape hatch is costly: the runner dropsWRITE_RESTRICTEDwhenever any DenyRead path is configured, because the kernel skips restricted-SID deny ACEs for reads under that flag, and a fully restricted token then cannot open executables. That is the same wall #640 hit.What this does
Gives the sandbox an identity of its own: a separate local account per workspace and role, in one managed group.
The inversion is the point. A separate account has no access to the caller's profile at all, so credential stores are unreachable by construction rather than by enumerating deny rules. The interesting direction becomes what to GRANT, and the same SID is what a write grant or a firewall rule keys to.
SeBatchLogonRight, and explicitly denies interactive, network, remote-interactive and service logon, so the account cannot be signed into even if its password leaked.LogonUseris pinned to"."so a same-named domain account is never picked up. A launch path built onCreateProcessWithLogonWwould need this policy revisited, which is one reason that path is a separate decision.CryptProtectData, since an ACL only binds while the filesystem is the one being asked and a backup or a mounted image would otherwise give it up in the clear. The principal name is the entropy, so a blob copied onto another principal's path fails to decrypt rather than authenticating the wrong account.zero sandbox execasks the same question before it plans, and agit cloneis refused as nested even under the default network policy, where the network prompt used to answer first. That coversinit,init-dbandclone, resolved the way git resolves them: an alias defined with-c, with--config-envor throughGIT_CONFIG_COUNT/GIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_nandGIT_CONFIG_PARAMETERSis expanded with git's own quoting and its in-alias option handling, chains are followed with cycle detection, and a definition the analyzer cannot read is refused rather than guessed at. A standalone workspace, which keeps its carveouts, is untouched. The guard is not containment of the.gitpathname, and does not have to be. A repository assembled by other means (mkdir and a few writes, an archive, a script) is not recognised, and no static reading of a shell command can recognise all of them. That is why the config and hooks carveouts are planned for a governed workspace too: the boundary is the deny ACE at write time, and this refusal is the layer that explains itself to an operator. An earlier commit skipped those carveouts to avoid creating a control directory inside a repository Zero does not own; that was restored once the consequence was measured and did not reproduce, and a test drives real git to keep it honest.Verification, and what is not verified
gofmt,go vet,go build ./...clean; builds for linux, darwin and windows. The package tests cover name derivation and truncation, password complexity, "already exists" handling, the raw Win32 struct layouts, LSA byte-vs-rune lengths, deny-before-allow ordering, trustee scoping, root grants, metadata materialization and identity-checked rollback, revocation, secret round-trip and overwrite, path traversal, idempotent removal, the launch refusal at both entry points, runtime-root creation and DACL restoration, and the nested-repository guard against real git spellings.Two of those matter most and do real work rather than asserting intent: one reads the stored secret's DACL back and fails if any trustee other than the owner and SYSTEM appears, and another asserts
SE_DACL_PROTECTEDso an inherited ACE cannot reach it.Honest caveats:
NetUserAdd,LsaAddAccountRights,NetUserDelandLogonUserall need administrator rights. Account and group creation were confirmed on a real elevated session before the launch gate; with the gate, the provisioning round-trip test (ZERO_WINDOWS_IDENTITY_PROVISION_TEST=1plus an elevation check) exercises them only with the launch seam opened.TestGrantLogonRightsAndMintPrincipalTokenhas not run to completion: Smart App Control on this machine blocks freshly built unsigned binaries, so it needs a clean elevated box. Everything that does not require elevation runs here, including the secret round-trip, which asserts the password does not appear verbatim in the stored bytes.Worth deciding before merge
Creating real local accounts is user-visible in a way the current sandbox is not: AV and EDR commonly flag
NetUserAdd, enterprise policy often blocks local account creation, and the accounts appear innet userand Settings. Provisioning is refused today, so none of that happens yet, but it should be a deliberate call before the launch path lands rather than a surprise in a merged PR.