Add service-managed package registration for Windows sandbox accounts (#45542)

## What changed

- Add an explicit `registered_core` provisioning mode that registers the app package for both managed sandbox accounts and records their runner aliases. Authenticate callers against the service's package family and installed version.
- Persist runtime ownership and publish readiness only after both registrations and AppData metadata grants succeed. Prevent legacy setup or another owner from replacing registered sandbox accounts, and restrict `refresh_only` requests to an existing ready setup.
- Scope service and pipe names by package identity.
- Preserve registrations across package updates and clean them up when the owner uninstalls the app. Fence provisioning during teardown and defer package removal until native cleanup succeeds and the service exits.

## Testing

Add tests for registration opt-in, ownership and readiness checks, legacy setup isolation, metadata ACL preservation, listener shutdown handling, and the cleanup finalizer's commit barrier and UTF-8 input.

GitOrigin-RevId: 69e52f7463285b51f3bef831f071245f0eca0838
This commit is contained in:
zm-oai authored and copyberry committed 2026-09-14 23:24:10 +00:00
1 parent 18d7ace221
commit 6ae5e71458
50 files changed
+3515 -169

No files matched your search

@@ -1,3 +1,4 @@
use crate::SandboxRuntimeAccount;
use crate::dpapi;
use crate::logging::debug_log;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
@@ -20,13 +21,19 @@ use crate::winutil::local_user_flags;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::ensure;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use std::collections::HashMap;
use std::fs;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
use windows_sys::Win32::Security::LOGON32_LOGON_INTERACTIVE;
use windows_sys::Win32::Security::LOGON32_PROVIDER_DEFAULT;
use windows_sys::Win32::Security::LogonUserW;
#[cfg(test)]
#[path = "identity_integration_tests.rs"]
@@ -147,6 +154,54 @@ fn decode_password(record: &SandboxUserRecord) -> Result<String> {
Ok(pwd)
}
/// Opens a token for one existing managed account without provisioning or changing it.
/// The caller must keep the authenticated credential directory pinned and verify
/// the token's recorded SID, group membership, and non-administrator status.
pub fn logon_existing_sandbox_account(
codex_home: &Path,
account: SandboxRuntimeAccount,
) -> Result<OwnedHandle> {
// Unlike the ordinary app-side readers, this service recovery path must
// never create diagnostic files beneath an owner-controlled directory.
let marker: SetupMarker = serde_json::from_slice(
&fs::read(setup_marker_path(codex_home)).context("read sandbox setup marker")?,
)
.context("parse sandbox setup marker")?;
ensure!(
marker.version_matches(),
"sandbox setup marker is missing or incompatible"
);
let users: SandboxUsersFile = serde_json::from_slice(
&fs::read(sandbox_users_path(codex_home)).context("read sandbox accounts")?,
)
.context("parse sandbox accounts")?;
ensure!(users.version_matches(), "sandbox accounts are incompatible");
let record = match account {
SandboxRuntimeAccount::Offline => users.offline,
SandboxRuntimeAccount::Online => users.online,
};
ensure!(
record.username.eq_ignore_ascii_case(account.username()),
"sandbox account record does not match the managed account"
);
let password = crate::to_wide(decode_password(&record)?);
let mut token = 0;
if unsafe {
LogonUserW(
crate::to_wide(account.username()).as_ptr(),
crate::to_wide(".").as_ptr(),
password.as_ptr(),
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&mut token,
)
} == 0
{
return Err(std::io::Error::last_os_error()).context("log on existing sandbox account");
}
Ok(unsafe { OwnedHandle::from_raw_handle(token as _) })
}
fn select_identity(
network_identity: SandboxNetworkIdentity,
codex_home: &Path,
@@ -14,30 +14,29 @@ use serde::Serialize;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::System::Registry as registry;
use crate::runtime_ownership::RuntimeRegistration;
use crate::winutil::to_wide;
// Package updates can replace the service key, so keep this record outside it.
const INSTALLATION_KEY: &str = r"SOFTWARE\OpenAI\Codex\WindowsSandboxService";
const INSTALLATION_VALUE: &str = "ProvisionedInstallation";
pub const INSTALLATION_KEY: &str = r"SOFTWARE\OpenAI\Codex\WindowsSandboxService";
pub const INSTALLATION_VALUE: &str = "ProvisionedInstallation";
const MAX_VALUE_UNITS: usize = 4096;
#[derive(Clone, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DesktopInstallation {
pub created_codex_home: bool,
pub cache_home: PathBuf,
}
#[derive(Clone, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct InstallationRecord {
pub user_sid: String,
pub codex_home: PathBuf,
pub session_id: u32,
#[serde(default)]
pub desktop_installation: Option<DesktopInstallation>,
}
pub fn load() -> Result<Option<InstallationRecord>> {
load_from(INSTALLATION_KEY)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runtime: Option<RuntimeRegistration>,
}
pub(crate) fn load_from(key: &str) -> Result<Option<InstallationRecord>> {
@@ -75,10 +74,6 @@ pub(crate) fn load_from(key: &str) -> Result<Option<InstallationRecord>> {
Ok(Some(record))
}
pub fn save(record: &InstallationRecord) -> Result<()> {
save_to(INSTALLATION_KEY, record)
}
pub(crate) fn save_to(key: &str, record: &InstallationRecord) -> Result<()> {
let value = to_wide(
serde_json::to_string(record).context("serialize protected sandbox installation record")?,
@@ -104,19 +99,3 @@ pub(crate) fn save_to(key: &str, record: &InstallationRecord) -> Result<()> {
.context("persist protected sandbox installation record")
}
}
pub fn remove() -> Result<()> {
let status = unsafe {
registry::RegDeleteKeyW(
registry::HKEY_LOCAL_MACHINE,
to_wide(INSTALLATION_KEY).as_ptr(),
)
};
match status {
foundation::ERROR_SUCCESS
| foundation::ERROR_FILE_NOT_FOUND
| foundation::ERROR_PATH_NOT_FOUND => Ok(()),
status => Err(io::Error::from_raw_os_error(status as i32))
.context("remove protected sandbox installation record"),
}
}
+51 -6
View File
@@ -95,6 +95,34 @@ mod provisioning_client;
#[cfg(target_os = "windows")]
mod provisioning_protocol;
#[cfg(target_os = "windows")]
mod runtime_ownership;
#[cfg(target_os = "windows")]
mod service_identity;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::CORE_INSTALLATION_KEY;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::INSTALLATION_KEY;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::INSTALLATION_VALUE;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::RuntimeAccountRegistration;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::RuntimeRegistration;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::load_installation;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::remove_installation;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use runtime_ownership::save_installation;
#[cfg(target_os = "windows")]
mod resolved_permissions;
#[cfg(target_os = "windows")]
mod token;
@@ -146,6 +174,8 @@ mod setup_provisioning;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use setup_provisioning::main as setup_helper_main;
#[cfg(target_os = "windows")]
pub use setup_provisioning::provision_sandbox_in_process;
#[cfg(target_os = "windows")]
mod spawn_prep;
@@ -171,12 +201,6 @@ pub(crate) use elevated::runner_pipe;
pub use installation_record::DesktopInstallation;
#[cfg(target_os = "windows")]
pub use installation_record::InstallationRecord;
#[cfg(target_os = "windows")]
pub use installation_record::load as load_sandbox_installation;
#[cfg(target_os = "windows")]
pub use installation_record::remove as remove_sandbox_installation;
#[cfg(target_os = "windows")]
pub use installation_record::save as save_sandbox_installation;
#[cfg(target_os = "windows")]
pub use acl::add_deny_read_ace;
@@ -249,6 +273,8 @@ pub use hide_users::hide_current_user_profile_dir;
#[cfg(target_os = "windows")]
pub use hide_users::hide_newly_created_users;
#[cfg(target_os = "windows")]
pub use identity::logon_existing_sandbox_account;
#[cfg(target_os = "windows")]
pub use identity::require_logon_sandbox_creds;
#[cfg(target_os = "windows")]
pub use identity::sandbox_setup_is_complete;
@@ -335,6 +361,8 @@ pub use provisioning_protocol::PROVISIONING_PROTOCOL_VERSION;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::ProvisioningMessage;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::SANDBOX_GROUP_CHANGED;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::SANDBOX_PROVISIONING_PIPE_NAME;
#[cfg(target_os = "windows")]
pub use provisioning_protocol::SandboxProvisioningRequest;
@@ -353,6 +381,15 @@ pub use resolved_permissions::WindowsSandboxTokenMode;
#[cfg(target_os = "windows")]
pub use resolved_permissions::token_mode_for_permission_profile;
#[cfg(target_os = "windows")]
pub use runtime_ownership::APP_CORE_RUNNER_ALIAS;
#[cfg(target_os = "windows")]
pub use runtime_ownership::SandboxRuntimeAccount;
#[cfg(target_os = "windows")]
pub use service_identity::windows_sandbox_service_name;
#[cfg(target_os = "windows")]
pub use service_identity::windows_sandbox_service_pipe_name;
#[cfg(target_os = "windows")]
pub use setup::OFFLINE_USERNAME;
#[cfg(target_os = "windows")]
pub use setup::ONLINE_USERNAME;
@@ -363,6 +400,8 @@ pub use setup::SandboxSetupRequest;
#[cfg(target_os = "windows")]
pub use setup::SetupRootOverrides;
#[cfg(target_os = "windows")]
pub use setup::SetupRuntime;
#[cfg(target_os = "windows")]
pub use setup::run_elevated_provisioning_setup;
#[cfg(target_os = "windows")]
pub use setup::run_elevated_provisioning_setup_with_retained_handles;
@@ -402,6 +441,8 @@ pub use stdio_bridge::forward_sandbox_session_stdio;
#[doc(hidden)]
pub use token::LocalSid;
#[cfg(target_os = "windows")]
pub use token::TokenGroup;
#[cfg(target_os = "windows")]
pub use token::convert_string_sid_to_sid;
#[cfg(target_os = "windows")]
pub use token::create_readonly_token_with_cap_from;
@@ -416,6 +457,8 @@ pub use token::create_workspace_write_token_with_caps_from;
#[cfg(target_os = "windows")]
pub use token::get_current_token_for_restriction;
#[cfg(target_os = "windows")]
pub use token::token_groups;
#[cfg(target_os = "windows")]
pub use token_user::get_user_sid_bytes;
#[cfg(target_os = "windows")]
pub use unified_exec::WindowsSandboxSessionRequest;
@@ -432,6 +475,8 @@ pub use uninstall_windows::clean_up_packaged_windows_sandbox;
#[cfg(target_os = "windows")]
pub use uninstall_windows::prepare_packaged_windows_sandbox_cleanup;
#[cfg(target_os = "windows")]
pub use uninstall_windows::prepare_packaged_windows_sandbox_cleanup_with_retained_tokens;
#[cfg(target_os = "windows")]
pub use wfp::install_wfp_filters_for_account;
#[cfg(target_os = "windows")]
pub use wfp_setup::install_wfp_filters;
@@ -88,6 +88,18 @@ pub fn setup_log_writer(base_dir: &Path) -> Result<File> {
}
}
/// Release setup's retained handles under the setup lock, after its writers finish.
/// Keep the slot initialized so later diagnostics cannot reopen a caller-controlled path.
pub(crate) fn release_setup_log() -> Result<()> {
if let Some(log) = SETUP_LOG.get() {
let mut log = log
.lock()
.map_err(|_| anyhow::anyhow!("setup log lock poisoned"))?;
*log = None;
}
Ok(())
}
fn append_line(line: &str, base_dir: Option<&Path>) {
if let Some(log) = SETUP_LOG.get() {
if let Ok(mut log) = log.lock()
@@ -136,6 +148,54 @@ pub fn log_note(msg: &str, base_dir: Option<&Path>) {
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn setup_log_releases_handles_without_path_fallback() {
const CHILD_ENV: &str = "CODEX_TEST_SETUP_LOG_RELEASE_CHILD";
if std::env::var(CHILD_ENV).ok().as_deref() != Some("1") {
// SETUP_LOG is process-global; isolate this test from ordinary daily logging.
let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([
"--exact",
"logging::tests::setup_log_releases_handles_without_path_fallback",
"--nocapture",
])
.env(CHILD_ENV, "1")
.output()
.expect("run isolated setup-log test");
assert!(output.status.success(), "isolated test failed: {output:?}");
assert!(
String::from_utf8_lossy(&output.stdout).contains("setup-log release verified"),
"isolated test did not run: {output:?}"
);
return;
}
let tempdir = tempfile::tempdir().expect("tempdir");
let directory = tempdir.path().join(".sandbox");
std::fs::create_dir(&directory).expect("create sandbox directory");
drop(setup_log_writer(&directory).expect("open retained setup log"));
let error =
std::fs::remove_dir_all(&directory).expect_err("setup handles prevent deletion");
assert_eq!(
error.raw_os_error(),
Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32)
);
release_setup_log().expect("release setup log");
std::fs::remove_dir_all(&directory).expect("delete sandbox after releasing handles");
std::fs::create_dir(&directory).expect("recreate caller-controlled directory");
release_setup_log().expect("repeated release is harmless");
log_note("must not reopen the directory", Some(&directory));
assert!(
std::fs::read_dir(&directory)
.expect("read directory")
.next()
.is_none()
);
println!("setup-log release verified");
}
#[test]
fn preview_does_not_panic_on_utf8_boundary() {
@@ -32,9 +32,10 @@ use windows_sys::Win32::System::Pipes::GetNamedPipeServerProcessId;
use windows_sys::Win32::System::Pipes::WaitNamedPipeW;
use windows_sys::Win32::System::Services;
const SERVICE_NAME: &str = "CodexSandboxService";
const PROVISIONING_TIMEOUT: Duration = Duration::from_secs(120);
mod group_change;
impl WindowsSandboxProvisioningSettings {
/// Derives the full firewall settings using the same environment handling as elevated setup.
pub fn from_environment(
@@ -113,6 +114,8 @@ pub fn provision_windows_sandbox_via_service(
.to_str()
.context("sandbox provisioning home is not valid UTF-8")?
.to_owned(),
registered_core: false,
refresh_only: false,
settings,
listeners,
},
@@ -178,6 +181,12 @@ fn send_service_request(
}
Err(error) => return Err(error),
};
if matches!(&response, crate::SandboxProvisioningResponse::Error { message }
if message == crate::SANDBOX_GROUP_CHANGED)
{
drop(pipe);
return group_change::retry(request, deadline);
}
Ok(response)
}
@@ -211,15 +220,16 @@ fn exchange_request(
}
fn connect(deadline: Instant) -> anyhow::Result<Option<File>> {
let pipe_name = crate::windows_sandbox_service_pipe_name()?;
let open_pipe = || {
OpenOptions::new()
.read(true)
.write(true)
.custom_flags(SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION)
.open(crate::SANDBOX_PROVISIONING_PIPE_NAME)
.open(&pipe_name)
};
let pipe_name = crate::to_wide(crate::SANDBOX_PROVISIONING_PIPE_NAME);
let pipe_name = crate::to_wide(&pipe_name);
loop {
match open_pipe() {
Ok(pipe) => return Ok(Some(pipe)),
@@ -265,7 +275,7 @@ fn verify_server(pipe: HANDLE) -> anyhow::Result<()> {
}
let manager = ServiceHandle(manager);
let service_name = crate::to_wide(SERVICE_NAME);
let service_name = crate::to_wide(crate::windows_sandbox_service_name()?);
let service = unsafe {
Services::OpenServiceW(
manager.0,
@@ -0,0 +1,25 @@
//! Retry only the service's authenticated refusal before dispatch.
//! A lost response may follow a mutation, so the retry's transport errors stay errors.
use std::time::Duration;
use std::time::Instant;
use crate::FramedProvisioningMessage;
use crate::SandboxProvisioningResponse;
pub(super) fn retry(
request: &FramedProvisioningMessage,
deadline: Instant,
) -> anyhow::Result<SandboxProvisioningResponse> {
let mut pipe = loop {
if let Some(pipe) = super::connect(deadline)? {
break pipe;
}
anyhow::ensure!(
Instant::now() < deadline,
"refreshed sandbox service pipe is unavailable"
);
std::thread::sleep(Duration::from_millis(25));
};
super::exchange_request(&mut pipe, request, deadline)
}
@@ -13,6 +13,9 @@ pub const PROVISIONING_PROTOCOL_VERSION: u8 = 1;
/// Named pipe used by the machine-wide Windows sandbox provisioning service.
pub const SANDBOX_PROVISIONING_PIPE_NAME: &str = r"\\.\pipe\OpenAI.CodexSandbox";
/// Pre-dispatch refusal: the caller may reconnect once to the refreshed pipe.
pub const SANDBOX_GROUP_CHANGED: &str = "sandbox group changed before authentication";
/// Versioned provisioning-service message carried in a length-prefixed JSON frame.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FramedProvisioningMessage {
@@ -42,6 +45,12 @@ pub enum ProvisioningMessage {
#[serde(deny_unknown_fields)]
pub struct SandboxProvisioningRequest {
pub codex_home: String,
/// Routing request; the service independently authenticates its installed caller.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub registered_core: bool,
/// Refresh an existing registration without creating or repairing sandbox accounts.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub refresh_only: bool,
pub settings: WindowsSandboxProvisioningSettings,
pub listeners: WindowsSandboxProxyListeners,
}
@@ -0,0 +1,208 @@
//! Shares the protected installation record with mutating sandbox setup.
//! Callers must hold the sandbox setup mutex while admitting or changing ownership.
use std::io;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize;
use serde::Serialize;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::System::Registry as registry;
/// Selects legacy helper materialization or verified app-contained Core for setup.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SetupRuntime {
#[default]
Legacy,
Registered,
}
impl SetupRuntime {
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde requires a borrowed field"
)]
pub(crate) fn is_legacy(&self) -> bool {
*self == Self::Legacy
}
}
/// Package-scoped execution alias declared for the app's sandbox runner.
pub const APP_CORE_RUNNER_ALIAS: &str = "codex-core-command-runner.exe";
/// The service may register its package only for these managed sandbox accounts.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxRuntimeAccount {
Offline,
Online,
}
impl SandboxRuntimeAccount {
pub fn username(self) -> &'static str {
match self {
Self::Offline => crate::setup::OFFLINE_USERNAME,
Self::Online => crate::setup::ONLINE_USERNAME,
}
}
}
pub use crate::installation_record::INSTALLATION_KEY;
pub use crate::installation_record::INSTALLATION_VALUE;
use crate::installation_record::InstallationRecord;
use crate::winutil::to_wide;
// Old services overwrite the parent value and delete its key on uninstall.
// A child key preserves Core state and makes that old whole-key delete fail.
pub const CORE_INSTALLATION_KEY: &str =
r"SOFTWARE\OpenAI\Codex\WindowsSandboxService\RegisteredCore";
/// Written before registration so a service restart cannot lose cleanup ownership.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeRegistration {
pub package_family: String,
pub accounts: Vec<RuntimeAccountRegistration>,
/// Owner-authorized AppData roots, recorded before granting metadata access.
/// Retain former roots through redirection and package updates until cleanup.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metadata_roots: Vec<std::path::PathBuf>,
/// Committed only after both registrations and metadata grants succeed.
#[serde(default)]
pub ready_package: Option<String>,
/// Fences setup during normal teardown; a restart must not replay it.
/// Old non-null phase journals fail to decode rather than lose their fence.
#[serde(default, alias = "cleanup")]
pub retiring: Option<String>,
}
impl RuntimeRegistration {
pub fn ready_for_package(&self, full_name: &str) -> bool {
self.retiring.is_none()
&& self.ready_package.as_deref() == Some(full_name)
&& self.accounts.len() == 2
&& self.accounts[0].account != self.accounts[1].account
&& self
.accounts
.iter()
.all(|account| account.alias_path.is_some())
}
}
impl InstallationRecord {
pub fn runtime(&self) -> Result<&RuntimeRegistration> {
self.runtime
.as_ref()
.context("registered runtime ownership is missing")
}
pub fn runtime_mut(&mut self) -> Result<&mut RuntimeRegistration> {
self.runtime
.as_mut()
.context("registered runtime ownership is missing")
}
/// Any persisted cleanup has committed to removing this resource generation.
pub fn admit_owner(&self, owner: &InstallationRecord, family: &str) -> Result<()> {
ensure!(
self.user_sid == owner.user_sid
&& self.codex_home == owner.codex_home
&& self.runtime()?.package_family.eq_ignore_ascii_case(family),
"registered sandbox resources belong to a different owner or package"
);
ensure!(
self.runtime()?.retiring.is_none(),
"registered sandbox cleanup must finish before provisioning"
);
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeAccountRegistration {
pub account: SandboxRuntimeAccount,
pub user_sid: String,
/// OS-resolved alias written by the service, never inferred from a user name.
#[serde(default)]
pub alias_path: Option<std::path::PathBuf>,
}
/// Core owns its complete record; the old parent is only a fallback before/after Core.
pub fn load_installation() -> Result<Option<InstallationRecord>> {
if let Some(record) = crate::installation_record::load_from(CORE_INSTALLATION_KEY)? {
ensure!(
record.runtime.is_some(),
"Core installation record is missing runtime state"
);
return Ok(Some(record));
}
crate::installation_record::load_from(INSTALLATION_KEY)
}
/// Retires only legacy ownership while the caller holds the setup lock.
/// Registered Core ownership belongs to its post-service-exit finalizer.
pub fn remove_installation() -> Result<()> {
let Some(record) = load_installation()? else {
return Ok(());
};
ensure!(
record.runtime.is_none(),
"registered Core ownership must be retired after service exit"
);
let status = unsafe {
registry::RegDeleteKeyValueW(
registry::HKEY_LOCAL_MACHINE,
to_wide(INSTALLATION_KEY).as_ptr(),
to_wide(INSTALLATION_VALUE).as_ptr(),
)
};
match status {
foundation::ERROR_SUCCESS
| foundation::ERROR_FILE_NOT_FOUND
| foundation::ERROR_PATH_NOT_FOUND => flush_installation(INSTALLATION_KEY),
status => Err(io::Error::from_raw_os_error(status as i32))
.context("remove protected legacy sandbox installation record"),
}
}
/// Persists and flushes ownership before an operation may outlive this service.
/// The caller must hold the sandbox setup mutex across its read/modify/write.
pub fn save_installation(record: &InstallationRecord) -> Result<()> {
let key = if record.runtime.is_some() {
CORE_INSTALLATION_KEY
} else {
INSTALLATION_KEY
};
crate::installation_record::save_to(key, record)?;
flush_installation(key)
}
fn flush_installation(path: &str) -> Result<()> {
let mut key = 0;
let status = unsafe {
registry::RegOpenKeyExW(
registry::HKEY_LOCAL_MACHINE,
to_wide(path).as_ptr(),
0,
registry::KEY_QUERY_VALUE,
&mut key,
)
};
if status != foundation::ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32))
.context("open runtime ownership record");
}
let status = unsafe { registry::RegFlushKey(key) };
unsafe { registry::RegCloseKey(key) };
if status != foundation::ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32))
.context("flush runtime ownership record");
}
Ok(())
}
#[cfg(test)]
#[path = "runtime_ownership_tests.rs"]
mod tests;
@@ -0,0 +1,241 @@
//! Tests owner admission, readiness receipts, and backward-compatible record decoding.
use super::*;
use crate::DesktopInstallation;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
fn record() -> InstallationRecord {
InstallationRecord {
user_sid: "S-1-5-21-1-2-3-1000".into(),
codex_home: PathBuf::from(r"C:\Users\owner\.codex"),
session_id: 1,
desktop_installation: Some(DesktopInstallation {
created_codex_home: true,
cache_home: PathBuf::from(r"C:\Users\owner\.cache"),
}),
runtime: Some(RuntimeRegistration {
package_family: "OpenAI.Codex_publisher".into(),
metadata_roots: Vec::new(),
ready_package: None,
accounts: vec![RuntimeAccountRegistration {
account: SandboxRuntimeAccount::Offline,
user_sid: "S-1-5-21-1-2-3-1001".into(),
alias_path: None,
}],
retiring: None,
}),
}
}
fn pending() -> InstallationRecord {
let mut record = record();
record.runtime_mut().unwrap().retiring = Some("one-cleanup-generation".into());
record
}
const READY_PACKAGE: &str = "OpenAI.Codex_1.0.0.0_arm64__publisher";
fn ready_runtime() -> RuntimeRegistration {
let mut runtime = record().runtime.unwrap();
runtime.ready_package = Some(READY_PACKAGE.into());
runtime.accounts[0].alias_path = Some(PathBuf::from(r"C:\aliases\offline.exe"));
runtime.accounts.push(RuntimeAccountRegistration {
account: SandboxRuntimeAccount::Online,
user_sid: "S-1-5-21-1-2-3-1002".into(),
alias_path: Some(PathBuf::from(r"C:\aliases\online.exe")),
});
runtime
}
#[test]
fn readiness_requires_a_receipt_for_the_current_package_version() {
let mut runtime = ready_runtime();
assert!(runtime.ready_for_package(READY_PACKAGE));
assert!(!runtime.ready_for_package("OpenAI.Codex_2.0.0.0_arm64__publisher"));
runtime.ready_package = None;
assert!(!runtime.ready_for_package(READY_PACKAGE));
}
#[test]
fn readiness_requires_both_distinct_account_receipts() {
let mut missing_account = ready_runtime();
missing_account.accounts.pop();
let mut missing_alias = ready_runtime();
missing_alias.accounts[1].alias_path = None;
let mut duplicate_role = ready_runtime();
duplicate_role.accounts[1].account = SandboxRuntimeAccount::Offline;
let mut extra_account = ready_runtime();
extra_account
.accounts
.push(extra_account.accounts[0].clone());
for runtime in [
missing_account,
missing_alias,
duplicate_role,
extra_account,
] {
assert!(!runtime.ready_for_package(READY_PACKAGE));
}
}
#[test]
fn readiness_is_revoked_by_the_retirement_fence() {
let mut runtime = ready_runtime();
runtime.retiring = Some("one-cleanup-generation".into());
assert!(!runtime.ready_for_package(READY_PACKAGE));
}
#[test]
fn admission_accepts_package_family_casing() {
for stored in ["OpenAI.Codex_publisher", "openai.codex_PUBLISHER"] {
let mut record = record();
record.runtime_mut().unwrap().package_family = stored.into();
let expected = record.clone();
for requested in ["OpenAI.Codex_publisher", "OPENAI.CODEX_PUBLISHER"] {
record.admit_owner(&record.clone(), requested).unwrap();
assert_eq!(record, expected);
}
}
}
#[test]
fn admission_rejects_other_owner_home_and_family() {
let record = record();
let expected = record.clone();
for (home, sid, family) in [
(
record.codex_home.as_path(),
"S-1-5-21-1-2-3-2000",
record.runtime().unwrap().package_family.as_str(),
),
(
std::path::Path::new(r"C:\Users\owner\other"),
record.user_sid.as_str(),
record.runtime().unwrap().package_family.as_str(),
),
(
record.codex_home.as_path(),
record.user_sid.as_str(),
"OpenAI.CodexBeta_publisher",
),
(
record.codex_home.as_path(),
record.user_sid.as_str(),
"OpenAI.Codex_otherpublisher",
),
] {
let mut requested = record.clone();
requested.codex_home = home.to_path_buf();
requested.user_sid = sid.to_owned();
assert!(record.admit_owner(&requested, family).is_err());
assert_eq!(record, expected);
}
}
#[test]
fn returned_owner_cannot_cancel_a_persisted_retirement_fence() {
let expected = pending();
let journal = serde_json::to_string(&expected).unwrap();
let restored: InstallationRecord = serde_json::from_str(&journal).unwrap();
let returning_owner = record();
assert!(
restored
.admit_owner(
&returning_owner,
&returning_owner.runtime().unwrap().package_family
)
.is_err()
);
assert_eq!(restored, expected);
}
#[test]
fn journal_round_trip_retains_desktop_ownership_and_retirement_fence() {
for record in [record(), pending()] {
let json = serde_json::to_string(&record).unwrap();
assert_eq!(
serde_json::from_str::<InstallationRecord>(&json).unwrap(),
record
);
}
}
#[test]
fn production_record_without_optional_core_or_desktop_fields_still_loads() {
let mut expected = record();
expected.runtime = None;
expected.desktop_installation = None;
let json = r#"{"user_sid":"S-1-5-21-1-2-3-1000","codex_home":"C:\\Users\\owner\\.codex","session_id":1}"#;
assert_eq!(
serde_json::from_str::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn metadata_root_history_survives_record_round_trip() {
let mut expected = record();
expected.runtime_mut().unwrap().metadata_roots = vec![
PathBuf::from(r"C:\Users\owner\AppData\Roaming"),
PathBuf::from(r"D:\Redirected\Roaming"),
];
for record in [expected.clone(), {
let mut updated = expected;
updated.runtime_mut().unwrap().ready_package = Some(READY_PACKAGE.into());
updated
}] {
let json = serde_json::to_string(&record).unwrap();
assert_eq!(
serde_json::from_str::<InstallationRecord>(&json).unwrap(),
record
);
}
}
#[test]
fn older_runtime_receipts_default_to_no_recorded_metadata_roots() {
let expected = record();
let json = serde_json::to_value(&expected).unwrap();
assert!(json["runtime"].get("metadata_roots").is_none());
assert_eq!(
serde_json::from_value::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn legacy_null_cleanup_alias_preserves_the_active_record() {
let expected = record();
let mut json = serde_json::to_value(&expected).unwrap();
let runtime = json["runtime"].as_object_mut().unwrap();
runtime.remove("retiring");
runtime.insert("cleanup".into(), serde_json::Value::Null);
assert_eq!(
serde_json::from_value::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn legacy_non_null_cleanup_journal_cannot_silently_drop_its_fence() {
for stage in ["native_started", "native_complete"] {
let mut json = serde_json::to_value(record()).unwrap();
let runtime = json["runtime"].as_object_mut().unwrap();
runtime.remove("retiring");
let accounts = runtime["accounts"].clone();
runtime.insert(
"cleanup".into(),
serde_json::json!({
"id": "one-cleanup-generation",
"stage": stage,
"accounts": accounts,
}),
);
assert!(serde_json::from_value::<InstallationRecord>(json).is_err());
}
}
@@ -0,0 +1,67 @@
//! Keep each packaged channel's service and pipe separate while accounts remain shared.
//! An unpackaged client may use a routing hint; service admission still verifies OS identity.
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use crate::package_identity::process_package_family;
/// SCM name matching the packaged application's manifest. Unpackaged callers keep
/// the legacy service lookup and may use ordinary elevated setup when it is absent.
pub fn windows_sandbox_service_name() -> Result<String> {
let Some(family) = service_package_family()? else {
return Ok("CodexSandboxService".into());
};
let (name, _) = family.rsplit_once('_').context("invalid package family")?;
Ok(format!("CodexSandboxService.{name}"))
}
/// The full family, including publisher identity, qualifies the authenticated pipe.
pub fn windows_sandbox_service_pipe_name() -> Result<String> {
Ok(match service_package_family()? {
Some(family) => format!("{}.{}", crate::SANDBOX_PROVISIONING_PIPE_NAME, family),
None => crate::SANDBOX_PROVISIONING_PIPE_NAME.into(),
})
}
pub(crate) fn current_family() -> Result<Option<String>> {
unsafe { process_package_family(GetCurrentProcess()) }
}
fn service_package_family() -> Result<Option<String>> {
if let Some(family) = current_family()? {
return Ok(Some(family));
}
let Some(hint) = std::env::var_os("CODEX_WINDOWS_SANDBOX_PACKAGE_FAMILY") else {
return Ok(None);
};
let family = hint
.to_str()
.context("service package family is not UTF-8")?;
validate_service_family_hint(family)?;
// Lookup only: SCM/pipe verification and registered-client admission use OS identity.
Ok(Some(family.to_owned()))
}
fn validate_service_family_hint(family: &str) -> Result<()> {
let (name, publisher) = family
.rsplit_once('_')
.context("invalid service package family")?;
ensure!(
!name.is_empty()
&& name.len() <= 50
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-'))
&& publisher.len() == 13
&& publisher.bytes().all(|c| c.is_ascii_alphanumeric()),
"invalid service package family"
);
Ok(())
}
#[cfg(test)]
#[path = "service_identity_tests.rs"]
mod tests;
@@ -0,0 +1,26 @@
use super::validate_service_family_hint;
#[test]
fn service_routing_accepts_package_families() {
for family in [
"OpenAI.Codex_3k8sg7r9htsxt",
"OpenAI.CodexBeta_jabp31b5fhs74",
] {
assert!(validate_service_family_hint(family).is_ok());
}
}
#[test]
fn service_routing_rejects_paths_and_malformed_families() {
for family in [
"",
"_3k8sg7r9htsxt",
"OpenAI.Codex_bad",
"OpenAI.Codex_3k8sg7r9htsxt\\child",
"..\\OpenAI.Codex_3k8sg7r9htsxt",
"OpenAI.Codex_extra_3k8sg7r9htsxt",
"OpenAI.Codex\0_3k8sg7r9htsxt",
] {
assert!(validate_service_family_hint(family).is_err(), "{family:?}");
}
}
+6
View File
@@ -1,3 +1,4 @@
pub use crate::runtime_ownership::SetupRuntime;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeSet;
@@ -350,6 +351,7 @@ fn run_setup_refresh_inner(
otel: None,
real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()),
mode: SetupMode::Full,
runtime: SetupRuntime::Legacy,
refresh_only: true,
};
let json = serde_json::to_vec(&payload)?;
@@ -690,6 +692,8 @@ struct ElevationPayload {
otel: Option<codex_otel::StatsigMetricsSettings>,
real_user: String,
mode: SetupMode,
#[serde(default, skip_serializing_if = "SetupRuntime::is_legacy")]
runtime: SetupRuntime,
#[serde(default)]
refresh_only: bool,
}
@@ -1096,6 +1100,7 @@ fn elevated_provisioning_payload(
real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()),
otel: codex_otel::global_statsig_metrics_settings(),
mode: SetupMode::InteractiveProvision,
runtime: SetupRuntime::Legacy,
refresh_only: false,
}
}
@@ -1167,6 +1172,7 @@ pub fn run_elevated_provisioning_setup_with_retained_handles(
otel: codex_otel::global_statsig_metrics_settings(),
real_user: real_user.to_string(),
mode: SetupMode::ProvisionOnly,
runtime: SetupRuntime::Legacy,
refresh_only: false,
};
run_setup_exe(
@@ -1,7 +1,10 @@
//! Implements the Windows setup helper behind its shared library entrypoint.
//! Payload validation and all provisioning modes retain the helper contract.
//! Privileged sandbox setup shared by the setup helper and the service's ProvisionOnly path.
//! Full and read-ACL setup remain helper entrypoints; only they may launch a read-ACL child.
//! Command-line account provisioning cannot enter the service's admitted Core path.
mod firewall;
mod service;
pub use service::provision_sandbox_in_process;
mod read_acl_mutex;
use crate::DirectoryOpenDisposition;
@@ -9,6 +12,7 @@ use crate::SETUP_VERSION;
use crate::SetupErrorCode;
use crate::SetupErrorReport;
use crate::SetupFailure;
use crate::SetupRuntime;
use crate::acquire_sandbox_setup_lock;
use crate::add_deny_write_ace;
use crate::convert_string_sid_to_sid;
@@ -99,6 +103,7 @@ use sandbox_users::provision_sandbox_users;
use sandbox_users::resolve_sandbox_users_group_sid;
use sandbox_users::sid_bytes_to_psid;
// Legacy omits runtime; readers default its absence to Legacy.
#[derive(Debug, Clone, Deserialize, Serialize)]
struct Payload {
version: u32,
@@ -120,6 +125,8 @@ struct Payload {
real_user: String,
#[serde(default)]
mode: SetupMode,
#[serde(default, skip_serializing_if = "SetupRuntime::is_legacy")]
runtime: SetupRuntime,
#[serde(default)]
refresh_only: bool,
}
@@ -134,6 +141,16 @@ enum SetupMode {
ReadAclsOnly,
}
impl SetupMode {
fn provisions_accounts(self, refresh_only: bool) -> bool {
match self {
Self::ProvisionOnly | Self::InteractiveProvision => true,
Self::Full => !refresh_only,
Self::ReadAclsOnly => false,
}
}
}
#[derive(Clone, Copy)]
enum DaclInheritance {
Inherited,
@@ -519,6 +536,24 @@ fn real_main(setup_mode: &mut Option<SetupMode>) -> Result<()> {
),
)));
}
// Only this entry parses command-line JSON. Keep admission locked through
// the entire account-provisioning operation, including initial Full setup.
// The in-process adapter enters separately after authenticated service admission.
let _setup_guard = if payload.mode.provisions_accounts(payload.refresh_only) {
let guard = acquire_sandbox_setup_lock(INFINITE)?;
anyhow::ensure!(
payload.runtime == SetupRuntime::Legacy,
"registered Core requires service-owned provisioning"
);
anyhow::ensure!(
crate::runtime_ownership::load_installation()?
.is_none_or(|record| record.runtime.is_none()),
"registered Core owns these sandbox accounts; helper provisioning is not permitted"
);
Some(guard)
} else {
None
};
run_payload(&payload)
}
@@ -817,6 +852,9 @@ fn lock_persistent_sandbox_dirs(payload: &Payload, sandbox_group_sid: &[u8]) ->
}
fn lock_sandbox_bin_dir(payload: &Payload, sandbox_group_sid: &[u8]) -> Result<()> {
if payload.runtime == SetupRuntime::Registered {
return Ok(());
}
// The owner's unelevated refresh must be able to reapply this protected DACL.
lock_sandbox_dir(
&sandbox_bin_dir(&payload.codex_home),
@@ -1128,6 +1166,10 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res
#[path = "setup_provisioning/acl_tests.rs"]
mod acl_tests;
#[cfg(test)]
#[path = "setup_provisioning/registered_tests.rs"]
mod registered_tests;
#[cfg(test)]
mod tests {
use super::Payload;
@@ -1149,7 +1191,7 @@ mod tests {
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Storage::FileSystem::FILE_DELETE_CHILD;
fn payload_json() -> serde_json::Value {
pub(super) fn payload_json() -> serde_json::Value {
json!({
"version": SETUP_VERSION,
"offline_username": "CodexSandboxOffline",
@@ -7,6 +7,7 @@ use super::GRANT_ACCESS;
use super::Payload;
use super::SETUP_VERSION;
use super::SetupMode;
use super::SetupRuntime;
use super::convert_string_sid_to_sid;
use super::lock_sandbox_bin_dir;
use super::lock_sandbox_dir;
@@ -89,6 +90,7 @@ fn lock_sandbox_dir_blocks_inherited_write_for_runner_files() {
otel: None,
real_user,
mode: setup_mode,
runtime: SetupRuntime::Legacy,
refresh_only: false,
};
lock_sandbox_bin_dir(&payload, &sandbox_group_sid).expect("lock sandbox bin");
@@ -1,6 +1,7 @@
use anyhow::Result;
use std::io::Write;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::Foundation::S_OK;
use windows::Win32::Foundation::VARIANT_TRUE;
use windows::Win32::NetworkManagement::WindowsFirewall::INetFwPolicy2;
@@ -58,25 +59,31 @@ struct BlockRuleSpec<'a> {
remote_ports: Option<&'a str>,
}
// Balance successful COM initialization on every return path.
struct FirewallComApartment;
// Firewall COM also supports the service's existing MTA. Balance only our own initialization.
struct FirewallComApartment {
initialized: bool,
}
impl FirewallComApartment {
fn initialize() -> Result<Self> {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
if hr.is_err() {
if hr.is_err() && hr != RPC_E_CHANGED_MODE {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallComInitFailed,
format!("CoInitializeEx failed: {hr:?}"),
)));
}
Ok(Self)
Ok(Self {
initialized: hr.is_ok(),
})
}
}
impl Drop for FirewallComApartment {
fn drop(&mut self) {
unsafe { CoUninitialize() };
if self.initialized {
unsafe { CoUninitialize() };
}
}
}
@@ -490,6 +497,10 @@ fn log_line(log: &mut dyn Write, msg: &str) -> Result<()> {
Ok(())
}
#[cfg(test)]
#[path = "firewall_apartment_tests.rs"]
mod apartment_tests;
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
@@ -0,0 +1,40 @@
//! Verifies firewall COM access preserves a service thread's existing apartment.
use super::CLSCTX_INPROC_SERVER;
use super::CoCreateInstance;
use super::FirewallComApartment;
use super::INetFwPolicy2;
use super::NetFwPolicy2;
use pretty_assertions::assert_eq;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::System::Com::COINIT_APARTMENTTHREADED;
use windows::Win32::System::Com::COINIT_MULTITHREADED;
use windows::Win32::System::Com::CoInitializeEx;
use windows::Win32::System::Com::CoUninitialize;
#[test]
fn firewall_access_preserves_the_services_existing_mta() {
std::thread::spawn(|| {
let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
assert!(initialized.is_ok(), "initialize MTA: {initialized:?}");
// Open the rules collection without adding, changing, or deleting a rule.
let result = (|| -> anyhow::Result<()> {
let _apartment = FirewallComApartment::initialize()?;
let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER)? };
let _rules = unsafe { policy.Rules()? };
Ok(())
})();
let apartment = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
unsafe { CoUninitialize() };
assert_eq!(
apartment, RPC_E_CHANGED_MODE,
"caller's MTA must remain initialized"
);
result.expect("read firewall rules from the existing MTA");
})
.join()
.expect("firewall COM test thread");
}
@@ -0,0 +1,91 @@
//! Registration-specific setup serialization and legacy-materialization boundaries.
use super::Payload;
use super::tests::payload_json;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::fs;
#[test]
fn payload_runtime_wire_normalization_preserves_opt_in() {
let mut payload: Payload = serde_json::from_value(payload_json()).unwrap();
assert_eq!(payload.runtime, super::SetupRuntime::Legacy);
let legacy = serde_json::to_value(&payload).unwrap();
assert!(legacy.get("runtime").is_none());
let mut explicit = legacy.clone();
explicit["runtime"] = serde_json::json!("legacy");
let decoded: Payload = serde_json::from_value(explicit).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), legacy);
payload.runtime = super::SetupRuntime::Registered;
let mut registered = legacy.clone();
registered["runtime"] = serde_json::json!("registered");
assert_eq!(serde_json::to_value(&payload).unwrap(), registered);
let decoded: Payload = serde_json::from_value(registered.clone()).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), registered);
for invalid in [
serde_json::Value::Null,
serde_json::json!(true),
serde_json::json!("unverified"),
] {
let mut malformed = legacy.clone();
malformed["runtime"] = invalid;
assert!(serde_json::from_value::<Payload>(malformed).is_err());
}
}
#[test]
fn registered_payload_never_creates_or_locks_legacy_bin() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut json = payload_json();
json["codex_home"] = json!(tmp.path());
json["runtime"] = json!("registered");
let payload: Payload = serde_json::from_value(json).expect("registered payload");
// An empty SID would fail any ACL operation; Registered must not attempt one.
super::lock_sandbox_bin_dir(&payload, &[]).expect("no legacy bin work");
let bin = super::sandbox_bin_dir(tmp.path());
assert!(!bin.exists());
fs::create_dir(&bin).expect("existing legacy bin");
let sentinel = bin.join("sentinel");
fs::write(&sentinel, b"unchanged").expect("existing content");
super::lock_sandbox_bin_dir(&payload, &[]).expect("leave existing bin alone");
assert_eq!(fs::read(sentinel).expect("read sentinel"), b"unchanged");
}
#[test]
fn unverified_payload_cannot_create_legacy_bin() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut json = payload_json();
json["codex_home"] = json!(tmp.path());
json["runtime"] = json!("unverified");
assert!(serde_json::from_value::<Payload>(json).is_err());
assert!(!super::sandbox_bin_dir(tmp.path()).exists());
}
#[test]
fn helper_account_gate_covers_actual_provisioning_modes() {
for (mode, expected) in [
(super::SetupMode::Full, [true, false]),
(super::SetupMode::InteractiveProvision, [true, true]),
(super::SetupMode::ProvisionOnly, [true, true]),
(super::SetupMode::ReadAclsOnly, [false, false]),
] {
assert_eq!(
[false, true].map(|refresh_only| mode.provisions_accounts(refresh_only)),
expected
);
}
}
#[test]
fn parsed_provision_only_cannot_claim_the_private_service_entry() {
let mut json = payload_json();
json["mode"] = json!("provision-only");
json["runtime"] = json!("registered");
json["refresh_only"] = json!(true);
json["service_admitted"] = json!(true);
let payload: Payload = serde_json::from_value(json).expect("payload");
assert!(payload.mode.provisions_accounts(payload.refresh_only));
assert_ne!(payload.runtime, super::SetupRuntime::Legacy);
}
@@ -0,0 +1,49 @@
//! Adapts authenticated service provisioning to the existing setup transaction.
//! The caller owns admission, directory pins, and the setup mutex.
use super::Payload;
use super::SetupMode;
use super::run_payload;
use crate::SETUP_VERSION;
use crate::SetupRuntime;
use crate::logging::log_note;
use crate::sandbox_dir;
use anyhow::Result;
use std::path::Path;
/// Runs the existing ProvisionOnly setup transaction without launching a helper process.
/// The caller authenticates the owner, retains directory protections, and holds the setup mutex
/// on this thread across registration. Firewall setup preserves the caller's COM apartment.
pub fn provision_sandbox_in_process(
codex_home: &Path,
real_user: &str,
settings: crate::WindowsSandboxProvisioningSettings,
runtime: SetupRuntime,
) -> Result<()> {
let payload = Payload {
version: SETUP_VERSION,
offline_username: crate::setup::OFFLINE_USERNAME.to_string(),
online_username: crate::setup::ONLINE_USERNAME.to_string(),
codex_home: codex_home.to_path_buf(),
command_cwd: codex_home.to_path_buf(),
read_roots: Vec::new(),
write_roots: Vec::new(),
deny_read_paths: Vec::new(),
deny_write_paths: Vec::new(),
proxy_ports: settings.proxy_ports,
allow_local_binding: settings.allow_local_binding,
otel: codex_otel::global_statsig_metrics_settings(),
real_user: real_user.to_string(),
mode: SetupMode::ProvisionOnly,
runtime,
refresh_only: false,
};
run_payload(&payload)?;
if let Err(err) = crate::setup_error::clear_setup_error_report(codex_home) {
log_note(
&format!("setup orchestrator: failed to clear setup_error.json after success: {err}"),
Some(&sandbox_dir(codex_home)),
);
}
Ok(())
}
+2 -2
View File
@@ -193,7 +193,7 @@ pub unsafe fn get_current_token_for_restriction() -> Result<HANDLE> {
/// An owned token group, including attributes such as enabled and deny-only.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct TokenGroup {
pub struct TokenGroup {
pub sid: Vec<u8>,
pub attributes: u32,
}
@@ -202,7 +202,7 @@ pub(crate) struct TokenGroup {
///
/// # Safety
/// `token` must remain a valid token handle with `TOKEN_QUERY` access during this call.
pub(crate) unsafe fn token_groups(token: HANDLE, max_bytes: u32) -> Result<Vec<TokenGroup>> {
pub unsafe fn token_groups(token: HANDLE, max_bytes: u32) -> Result<Vec<TokenGroup>> {
let mut needed = 0;
GetTokenInformation(token, TokenGroups, std::ptr::null_mut(), 0, &mut needed);
ensure!(
@@ -1,5 +1,6 @@
//! Stops sandbox work under the setup lock before removing its resources and protections.
use std::os::windows::io::BorrowedHandle;
use std::path::Path;
use anyhow::Result;
@@ -11,6 +12,7 @@ use crate::setup::ONLINE_USERNAME;
mod firewall;
mod principals;
mod processes;
mod retained_logons;
/// Removes sandbox resources created for one authenticated packaged installation.
/// Keep a supplied home and its ancestors pinned until `clean_up_desktop` starts.
@@ -23,7 +25,8 @@ pub fn clean_up_packaged_windows_sandbox(
}
/// Holds the setup lock after sandbox accounts are disabled, their processes
/// have exited, and their logon tokens have been released.
/// have exited, and all logon tokens except explicitly retained private cleanup
/// tokens have been released.
///
/// Keep this guard on the thread that acquired the setup lock. Callers must not
/// re-enable the accounts or create new sandbox logons before `finish`.
@@ -33,19 +36,34 @@ pub fn clean_up_packaged_windows_sandbox(
#[must_use = "finish cleanup or leave the sandbox accounts disabled with their protections intact"]
pub struct PreparedWindowsSandboxCleanup {
_setup_lock: crate::setup_mutex::SandboxSetupLock,
users: principals::DisabledSandboxUsers,
_retained_logons: retained_logons::RetainedLogons,
}
/// Disables sandbox accounts, stops their processes, and waits for their logon
/// tokens to be released.
/// Disables sandbox accounts and waits for their processes and logon tokens to exit.
///
/// No resources or protections are removed here. On failure, restoration of the
/// original account flags is attempted before the setup lock is released; any
/// restoration failure is included in the returned error.
pub fn prepare_packaged_windows_sandbox_cleanup() -> Result<PreparedWindowsSandboxCleanup> {
prepare_packaged_windows_sandbox_cleanup_with_retained_tokens(&[])
}
/// Retains only the trusted runtime finalizer's login tokens while stopping sandbox work.
/// These must be fresh, private logins used only by that SYSTEM cleanup process, never
/// runner tokens or logins shared with sandbox commands. Ordinary processes are still stopped.
/// The returned guard pins their identities until native cleanup finishes.
pub fn prepare_packaged_windows_sandbox_cleanup_with_retained_tokens(
tokens: &[BorrowedHandle<'_>],
) -> Result<PreparedWindowsSandboxCleanup> {
let setup_lock = crate::setup_mutex::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
let mut errors = Vec::new();
let mut users = principals::DisabledSandboxUsers::default();
if let Err(error) = users.disable().and_then(|()| processes::stop(&users)) {
let mut retained = retained_logons::RetainedLogons::default();
if let Err(error) = users.disable().and_then(|()| {
retained = retained_logons::RetainedLogons::capture(tokens, &users)?;
processes::stop(&users, &retained)
}) {
errors.push(format!("{error:#}"));
// No network protections have been removed, so failed preparation can restore these flags.
if let Err(error) = users.restore() {
@@ -56,6 +74,8 @@ pub fn prepare_packaged_windows_sandbox_cleanup() -> Result<PreparedWindowsSandb
Ok(PreparedWindowsSandboxCleanup {
_setup_lock: setup_lock,
users,
_retained_logons: retained,
})
}
@@ -64,16 +84,20 @@ impl PreparedWindowsSandboxCleanup {
///
/// Keep a supplied home and its ancestors pinned until `clean_up_desktop`
/// starts. Independent cleanup steps continue after an error, as in
/// `clean_up_packaged_windows_sandbox`.
/// `clean_up_packaged_windows_sandbox`. Retrying keeps the original account
/// identities; it must not adopt replacement accounts created between attempts.
pub fn finish(
self,
&self,
codex_home: Option<&Path>,
clean_up_desktop: impl FnOnce() -> Result<()>,
) -> Result<()> {
let _prepared = self;
self.users.validate_current()?;
let mut errors = Vec::new();
if let Some(codex_home) = codex_home {
if let Err(error) = crate::logging::release_setup_log() {
errors.push(format!("release setup log: {error:#}"));
}
for directory in [
crate::setup::sandbox_dir(codex_home),
crate::setup::sandbox_secrets_dir(codex_home),
@@ -5,6 +5,7 @@ use std::ptr::null;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use windows_sys::Win32::NetworkManagement::NetManagement as network;
use crate::setup::OFFLINE_USERNAME;
@@ -47,6 +48,21 @@ impl DisabledSandboxUsers {
self.users.iter().map(|user| user.sid.as_slice())
}
pub(super) fn validate_current(&self) -> Result<()> {
for name in [OFFLINE_USERNAME, ONLINE_USERNAME] {
let Some(flags) = local_user_flags(name)? else {
continue;
};
let captured = self.users.iter().find(|user| user.name == name);
ensure!(
captured.is_some_and(|user| resolve_sid(name).is_ok_and(|sid| sid == user.sid))
&& flags & network::UF_ACCOUNTDISABLE != 0,
"sandbox account changed after being disabled: {name}"
);
}
Ok(())
}
pub(super) fn restore(&self) -> Result<()> {
let mut errors = Vec::new();
for user in &self.users {
@@ -66,6 +82,20 @@ impl DisabledSandboxUsers {
}
}
#[cfg(test)]
impl DisabledSandboxUsers {
// In-memory admission fixture only; this does not resolve or change a local account.
pub(super) fn for_token_test(sid: Vec<u8>) -> Self {
Self {
users: vec![SandboxUser {
name: OFFLINE_USERNAME,
original_flags: network::UF_ACCOUNTDISABLE,
sid,
}],
}
}
}
pub(super) fn remove_sandbox_principal(name: &str) -> Result<()> {
let name_wide = to_wide(name);
let status = if name == "CodexSandboxUsers" {
@@ -1,4 +1,4 @@
//! Stops sandbox-account processes and waits for their logon tokens to be released.
//! Stops sandbox processes and drains logins except exact, pinned cleanup-owned tokens.
use std::ffi::c_void;
use std::io;
@@ -39,9 +39,10 @@ use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
use super::principals::DisabledSandboxUsers;
use super::retained_logons::RetainedLogons;
use crate::token::get_user_sid_bytes;
pub(super) fn stop(users: &DisabledSandboxUsers) -> Result<()> {
pub(super) fn stop(users: &DisabledSandboxUsers, retained: &RetainedLogons) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let processes = sandbox_processes(users)?;
@@ -80,8 +81,9 @@ pub(super) fn stop(users: &DisabledSandboxUsers) -> Result<()> {
drop(processes);
// A token can outlive its process or exist before a runner starts. Account disable does
// not revoke it, so release our handles and check for tokens before removing protections.
if !has_sandbox_logon_session(users)? {
// not revoke it, so check for remaining logins before removing protections. Only
// explicitly pinned, private SYSTEM-finalizer tokens may remain; no process is exempt.
if !has_sandbox_logon_session(users, retained)? {
return Ok(());
}
if Instant::now() >= deadline {
@@ -157,7 +159,10 @@ fn sandbox_processes(users: &DisabledSandboxUsers) -> Result<Vec<OwnedHandle>> {
Ok(handles)
}
fn has_sandbox_logon_session(users: &DisabledSandboxUsers) -> Result<bool> {
fn has_sandbox_logon_session(
users: &DisabledSandboxUsers,
retained: &RetainedLogons,
) -> Result<bool> {
let mut count = 0;
let mut logons = null_mut();
let status = unsafe { LsaEnumerateLogonSessions(&mut count, &mut logons) };
@@ -189,7 +194,7 @@ fn has_sandbox_logon_session(users: &DisabledSandboxUsers) -> Result<bool> {
let data = unsafe { &*data.0.cast::<SECURITY_LOGON_SESSION_DATA>() };
// LSA also lists sessions without a user SID, even before sandbox accounts exist.
// Only sessions identified as sandbox users are evidence of remaining sandbox tokens.
if is_sandbox_user(users, data.Sid) {
if is_sandbox_user(users, data.Sid) && !retained.contains(*logon) {
return Ok(true);
}
}
@@ -0,0 +1,77 @@
//! Pins only cleanup-owned login sessions; every other sandbox login still blocks cleanup.
use std::io;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::OwnedHandle;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::LUID;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::TOKEN_STATISTICS;
use windows_sys::Win32::Security::TokenStatistics;
use super::principals::DisabledSandboxUsers;
#[derive(Default)]
pub(super) struct RetainedLogons {
// Keeping each token open prevents its AuthenticationId from being recycled.
_tokens: Vec<OwnedHandle>,
ids: Vec<LUID>,
}
impl RetainedLogons {
pub(super) fn capture(
tokens: &[BorrowedHandle<'_>],
users: &DisabledSandboxUsers,
) -> Result<Self> {
ensure!(tokens.len() <= 2, "too many retained cleanup tokens");
let mut retained = Self::default();
let mut seen_sids = Vec::new();
for token in tokens {
let token = token.try_clone_to_owned()?;
let handle = token.as_raw_handle() as HANDLE;
let sid = unsafe { crate::token::get_user_sid_bytes(handle) }?;
ensure!(
users.sids().any(|candidate| candidate == sid.as_slice())
&& !seen_sids.contains(&sid),
"cleanup token does not identify a distinct managed sandbox account"
);
let mut stats: TOKEN_STATISTICS = unsafe { std::mem::zeroed() };
let mut returned = 0;
if unsafe {
GetTokenInformation(
handle,
TokenStatistics,
(&mut stats as *mut TOKEN_STATISTICS).cast(),
std::mem::size_of::<TOKEN_STATISTICS>() as u32,
&mut returned,
)
} == 0
{
return Err(io::Error::last_os_error()).context("identify retained cleanup login");
}
ensure!(
returned as usize == std::mem::size_of::<TOKEN_STATISTICS>(),
"unexpected cleanup token statistics length"
);
seen_sids.push(sid);
retained.ids.push(stats.AuthenticationId);
retained._tokens.push(token);
}
Ok(retained)
}
pub(super) fn contains(&self, id: LUID) -> bool {
self.ids
.iter()
.any(|held| held.LowPart == id.LowPart && held.HighPart == id.HighPart)
}
}
#[cfg(test)]
#[path = "retained_logons_tests.rs"]
mod tests;
@@ -0,0 +1,106 @@
//! Exercises retained-logon admission and ownership using read-only current-process tokens.
use super::super::principals::DisabledSandboxUsers;
use super::RetainedLogons;
use crate::token::get_user_sid_bytes;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use std::os::windows::io::AsHandle;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::LUID;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::OpenProcessToken;
fn current_process_token() -> Result<OwnedHandle> {
let mut raw = 0;
ensure!(
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,
"open current-process token: {}",
std::io::Error::last_os_error()
);
Ok(unsafe { OwnedHandle::from_raw_handle(raw as _) })
}
#[test]
fn matches_only_the_complete_retained_authentication_id() {
let retained = RetainedLogons {
_tokens: Vec::new(),
ids: vec![LUID {
LowPart: 17,
HighPart: 4,
}],
};
let observed = [
LUID {
LowPart: 17,
HighPart: 4,
},
LUID {
LowPart: 18,
HighPart: 4,
},
LUID {
LowPart: 17,
HighPart: 5,
},
LUID {
LowPart: 0,
HighPart: 0,
},
]
.map(|id| retained.contains(id));
assert_eq!(observed, [true, false, false, false]);
assert!(!RetainedLogons::default().contains(LUID {
LowPart: 17,
HighPart: 4
}));
}
#[test]
fn rejects_more_than_two_tokens_before_admission() -> Result<()> {
let token = current_process_token()?;
let error = RetainedLogons::capture(&[token.as_handle(); 3], &DisabledSandboxUsers::default())
.err()
.expect("three token inputs must be rejected");
assert_eq!(error.to_string(), "too many retained cleanup tokens");
Ok(())
}
#[test]
fn rejects_a_token_without_a_captured_managed_sid() -> Result<()> {
let token = current_process_token()?;
assert!(
RetainedLogons::capture(&[token.as_handle()], &DisabledSandboxUsers::default()).is_err()
);
Ok(())
}
#[test]
fn rejects_distinct_handles_for_the_same_managed_sid() -> Result<()> {
let token = current_process_token()?;
let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;
let users = DisabledSandboxUsers::for_token_test(sid);
let duplicate = token.as_handle().try_clone_to_owned()?;
RetainedLogons::capture(&[token.as_handle()], &users)?;
assert!(RetainedLogons::capture(&[token.as_handle(), duplicate.as_handle()], &users).is_err());
Ok(())
}
#[test]
fn retained_token_remains_queryable_after_the_borrowed_handle_is_closed() -> Result<()> {
let (retained, expected_sid) = {
let token = current_process_token()?;
let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;
let users = DisabledSandboxUsers::for_token_test(sid.clone());
(RetainedLogons::capture(&[token.as_handle()], &users)?, sid)
};
assert_eq!(retained._tokens.len(), 1);
let actual_sid = unsafe { get_user_sid_bytes(retained._tokens[0].as_raw_handle() as HANDLE) }?;
assert_eq!(actual_sid, expected_sid);
Ok(())
}