Register Windows desktop uninstall ownership before sandbox setup (#45224)

## Why

Desktop uninstall cleanup needs an installation owner even when the user has not signed in or configured the Windows sandbox. Recording ownership only during provisioning leaves those installations unregistered.

## What changed

- Add an authenticated installation registration request and attempt it during Windows desktop stdio initialization, with a five-second timeout before the initialization response.
- Persist ownership independently of provisioning, preserve existing desktop ownership, and prevent another user or home from replacing the registered owner.
- Validate write authority and retain directory handles and guards to protect the registered home against junction conversion through privileged cleanup.
- Preserve existing CLI homes during desktop uninstall while removing their `CodexSandboxUsers` ACL entries. Report ACL revocation errors and avoid propagating unchanged ACLs.
- Grant the owner `WRITE_DAC` on `.sandbox-bin` and allow elevated-helper fallback when older permissions need repair or the service cannot establish an uninstall watcher.

## Testing

Add tests for installation registration without sandbox settings and for preserving a child's null DACL when revoking an absent SID from its parent.

GitOrigin-RevId: fb48923e9d76758d1bf5b50c7305aa60f91629db
This commit is contained in:
chess authored and copyberry committed 2026-09-13 13:06:40 +00:00
1 parent 1715e55076
commit 36f0dbe796
20 files changed
+446 -146

No files matched your search

+29 -8
View File
@@ -899,7 +899,11 @@ pub unsafe fn add_deny_read_ace(path: &Path, psid: *mut c_void) -> Result<bool>
#[path = "acl_tests.rs"]
mod tests;
pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) {
/// Removes explicit ACEs for one SID and propagates the updated inherited ACL.
///
/// # Safety
/// Caller must pass a valid SID pointer and have authority to edit the target DACL.
pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) -> Result<()> {
let mut p_sd: *mut c_void = std::ptr::null_mut();
let mut p_dacl: *mut ACL = std::ptr::null_mut();
let code = GetNamedSecurityInfoW(
@@ -916,7 +920,14 @@ pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) {
if !p_sd.is_null() {
LocalFree(p_sd as HLOCAL);
}
return;
return acl_api_result(path, "GetNamedSecurityInfoW", code);
}
if p_dacl.is_null() {
// A null DACL has no ACE to revoke; replacing it with an empty ACL would deny access.
if !p_sd.is_null() {
LocalFree(p_sd as HLOCAL);
}
return Ok(());
}
let trustee = TRUSTEE_W {
pMultipleTrustee: std::ptr::null_mut(),
@@ -931,9 +942,17 @@ pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) {
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
explicit.Trustee = trustee;
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
if code2 == ERROR_SUCCESS {
let _ = SetNamedSecurityInfoW(
let result = acl_api_result(
path,
"SetEntriesInAclW",
SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl),
)
.and_then(|()| {
// REVOKE_ACCESS only removes ACEs. An unchanged ACL must not propagate inheritance.
if (*p_new_dacl).AceCount == (*p_dacl).AceCount {
return Ok(());
}
let code = SetNamedSecurityInfoW(
to_wide(path).as_ptr() as *mut u16,
1,
DACL_SECURITY_INFORMATION,
@@ -942,13 +961,15 @@ pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) {
p_new_dacl,
std::ptr::null_mut(),
);
if !p_new_dacl.is_null() {
LocalFree(p_new_dacl as HLOCAL);
}
acl_api_result(path, "SetNamedSecurityInfoW", code)
});
if !p_new_dacl.is_null() {
LocalFree(p_new_dacl as HLOCAL);
}
if !p_sd.is_null() {
LocalFree(p_sd as HLOCAL);
}
result
}
/// Grants RX to the null device for the given SID to support stdout/stderr redirection.
@@ -6,6 +6,15 @@ use pretty_assertions::assert_eq;
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::GetSecurityDescriptorControl;
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
use windows_sys::Win32::Security::SetFileSecurityW;
use windows_sys::Win32::Security::UNPROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
@@ -53,3 +62,51 @@ fn existing_deny_ace_is_visible_without_write_dac() {
.expect("read existing deny ACE");
assert!(already_present);
}
#[test]
fn revoking_absent_sid_preserves_child_null_dacl() {
let parent = tempfile::tempdir().expect("parent directory");
let child = parent.path().join("child");
std::fs::create_dir(&child).expect("child directory");
let sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("absent SID");
let other_sid = LocalSid::from_string("S-1-5-21-10-20-30-41").expect("inherited SID");
unsafe {
super::add_allow_ace(parent.path(), other_sid.as_ptr()).expect("inheritable parent ACE");
let mut descriptor = std::ptr::null_mut();
assert_ne!(
ConvertStringSecurityDescriptorToSecurityDescriptorW(
crate::winutil::to_wide("D:NO_ACCESS_CONTROL").as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
std::ptr::null_mut(),
),
0,
);
// The legacy setter preserves a null DACL without applying automatic inheritance.
let set = SetFileSecurityW(
crate::winutil::to_wide(&child).as_ptr(),
DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION,
descriptor,
);
LocalFree(descriptor as HLOCAL);
assert_ne!(set, 0, "set an unprotected null DACL");
for revoke in [false, true] {
if revoke {
super::revoke_ace(parent.path(), sid.as_ptr()).expect("revoke absent SID");
}
let (dacl, descriptor) = super::fetch_dacl_handle(&child).expect("child permissions");
let mut control = 0;
let mut revision = 0;
let valid = GetSecurityDescriptorControl(descriptor, &mut control, &mut revision);
LocalFree(descriptor as HLOCAL);
assert_ne!(valid, 0, "read child inheritance flags");
assert_eq!(control & SE_DACL_PROTECTED, 0, "child permits inheritance");
assert!(
dacl.is_null(),
"revocation must preserve the child's null DACL"
);
}
}
}
@@ -81,7 +81,7 @@ pub unsafe fn apply_deny_read_acls(paths: &[PathBuf], psid: *mut c_void) -> Resu
Ok(added) => added,
Err(err) => {
for added_path in &added_in_this_call {
revoke_ace(added_path, psid);
let _ = revoke_ace(added_path, psid);
}
return Err(err);
}
@@ -51,7 +51,7 @@ pub unsafe fn sync_persistent_deny_read_acls(
for path in previous_paths {
if !desired_keys.contains(&lexical_path_key(&path)) {
revoke_ace(&path, psid);
let _ = revoke_ace(&path, psid);
}
}
+4
View File
@@ -200,6 +200,8 @@ pub use acl::path_or_child_file_has_standard_user_mutation_allow;
#[cfg(target_os = "windows")]
pub use acl::path_write_aces_need_refresh;
#[cfg(target_os = "windows")]
pub use acl::revoke_ace;
#[cfg(target_os = "windows")]
pub use audit::apply_world_writable_scan_and_denies_for_permissions;
#[cfg(target_os = "windows")]
pub use cap::load_or_create_cap_sids;
@@ -319,6 +321,8 @@ pub use provisioning_client::WindowsSandboxProvisioningOutcome;
#[cfg(target_os = "windows")]
pub use provisioning_client::provision_windows_sandbox_via_service;
#[cfg(target_os = "windows")]
pub use provisioning_client::register_desktop_installation;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::FramedProvisioningMessage;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::PROVISIONING_PROTOCOL_VERSION;
@@ -119,9 +119,44 @@ pub fn provision_windows_sandbox_via_service(
},
};
let deadline = Instant::now() + PROVISIONING_TIMEOUT;
match send_service_request(request, PROVISIONING_TIMEOUT)? {
crate::SandboxProvisioningResponse::Ok => {
Ok(WindowsSandboxProvisioningOutcome::Provisioned)
}
crate::SandboxProvisioningResponse::Unavailable => {
Ok(WindowsSandboxProvisioningOutcome::Unavailable)
}
crate::SandboxProvisioningResponse::Error { message } => Err(anyhow!(message)),
}
}
/// Records desktop uninstall ownership without creating or enabling a sandbox.
pub fn register_desktop_installation(codex_home: &Path) -> anyhow::Result<()> {
let request = crate::FramedProvisioningMessage {
version: crate::PROVISIONING_PROTOCOL_VERSION,
message: crate::ProvisioningMessage::RegisterInstallationRequest {
codex_home: codex_home
.to_str()
.context("desktop home is not valid UTF-8")?
.to_owned(),
},
};
match send_service_request(request, Duration::from_secs(5))? {
crate::SandboxProvisioningResponse::Ok => Ok(()),
crate::SandboxProvisioningResponse::Unavailable => {
bail!("desktop uninstall registration service is unavailable")
}
crate::SandboxProvisioningResponse::Error { message } => Err(anyhow!(message)),
}
}
fn send_service_request(
request: crate::FramedProvisioningMessage,
timeout: Duration,
) -> anyhow::Result<crate::SandboxProvisioningResponse> {
let deadline = Instant::now() + timeout;
let Some(mut pipe) = connect(deadline)? else {
return Ok(WindowsSandboxProvisioningOutcome::Unavailable);
return Ok(crate::SandboxProvisioningResponse::Unavailable);
};
let response = (|| -> anyhow::Result<crate::FramedProvisioningMessage> {
verify_server(pipe.as_raw_handle() as HANDLE)
@@ -156,26 +191,18 @@ pub fn provision_windows_sandbox_via_service(
)
}) =>
{
return Ok(WindowsSandboxProvisioningOutcome::Unavailable);
return Ok(crate::SandboxProvisioningResponse::Unavailable);
}
Err(error) => return Err(error),
};
if response.version != crate::PROVISIONING_PROTOCOL_VERSION {
return Ok(WindowsSandboxProvisioningOutcome::Unavailable);
return Ok(crate::SandboxProvisioningResponse::Unavailable);
}
let crate::ProvisioningMessage::ProvisionSandboxResponse { payload } = response.message else {
bail!("unexpected sandbox provisioning response message");
};
match payload {
crate::SandboxProvisioningResponse::Ok => {
Ok(WindowsSandboxProvisioningOutcome::Provisioned)
}
crate::SandboxProvisioningResponse::Unavailable => {
Ok(WindowsSandboxProvisioningOutcome::Unavailable)
}
crate::SandboxProvisioningResponse::Error { message } => Err(anyhow!(message)),
}
Ok(payload)
}
fn connect(deadline: Instant) -> anyhow::Result<Option<File>> {
@@ -25,6 +25,10 @@ pub struct FramedProvisioningMessage {
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProvisioningMessage {
/// Records uninstall ownership without provisioning sandbox resources.
RegisterInstallationRequest {
codex_home: String,
},
ProvisionSandboxRequest {
payload: SandboxProvisioningRequest,
},
@@ -813,13 +813,14 @@ fn lock_persistent_sandbox_dirs(payload: &Payload, sandbox_group_sid: &[u8]) ->
}
fn lock_sandbox_bin_dir(payload: &Payload, sandbox_group_sid: &[u8]) -> Result<()> {
// The owner's unelevated refresh must be able to reapply this protected DACL.
lock_sandbox_dir(
&sandbox_bin_dir(&payload.codex_home),
&payload.real_user,
sandbox_group_sid,
GRANT_ACCESS,
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE,
FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE | WRITE_DAC,
DaclInheritance::Protected,
payload.mode,
)