aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
14
akode-rs/windows-sandbox-rs/src/bin/command_runner/main.rs
Normal file
14
akode-rs/windows-sandbox-rs/src/bin/command_runner/main.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(test)), windows_subsystem = "windows")]
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
win::main()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn main() {
|
||||
panic!("akode-command-runner is Windows-only");
|
||||
}
|
||||
731
akode-rs/windows-sandbox-rs/src/bin/command_runner/win.rs
Normal file
731
akode-rs/windows-sandbox-rs/src/bin/command_runner/win.rs
Normal file
@@ -0,0 +1,731 @@
|
||||
//! Windows command runner used by the **elevated** sandbox path.
|
||||
//!
|
||||
//! The CLI launches this binary under the sandbox user when Windows sandbox level is
|
||||
//! Elevated. It connects to the IPC pipes, reads the framed `SpawnRequest`, derives a
|
||||
//! restricted token from the sandbox user, and spawns the child process via ConPTY
|
||||
//! (`tty=true`) or pipes (`tty=false`). It then streams output frames back to the parent,
|
||||
//! accepts stdin/terminate frames, and emits a final exit frame. The legacy restricted‑token
|
||||
//! path spawns the child directly and does not use this runner.
|
||||
|
||||
#![allow(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
mod cwd_junction;
|
||||
#[cfg(test)]
|
||||
#[path = "win/input_loop_tests.rs"]
|
||||
mod input_loop_tests;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_utils_pty::JobObject;
|
||||
use akode_windows_sandbox::ConsoleMode;
|
||||
use akode_windows_sandbox::ErrorPayload;
|
||||
use akode_windows_sandbox::ErrorStage;
|
||||
use akode_windows_sandbox::ExitPayload;
|
||||
use akode_windows_sandbox::FramedMessage;
|
||||
use akode_windows_sandbox::IPC_PROTOCOL_VERSION;
|
||||
use akode_windows_sandbox::LaunchDesktop;
|
||||
use akode_windows_sandbox::LocalSid;
|
||||
use akode_windows_sandbox::Message;
|
||||
use akode_windows_sandbox::OutputPayload;
|
||||
use akode_windows_sandbox::OutputStream;
|
||||
use akode_windows_sandbox::PipeSpawnHandles;
|
||||
use akode_windows_sandbox::ResizePayload;
|
||||
use akode_windows_sandbox::SpawnReady;
|
||||
use akode_windows_sandbox::SpawnRequest;
|
||||
use akode_windows_sandbox::StderrMode;
|
||||
use akode_windows_sandbox::StdinMode;
|
||||
use akode_windows_sandbox::WindowsSandboxTokenMode;
|
||||
use akode_windows_sandbox::allow_null_device;
|
||||
use akode_windows_sandbox::create_readonly_token_with_caps_and_user_from;
|
||||
use akode_windows_sandbox::create_workspace_write_token_with_caps_and_user_from;
|
||||
use akode_windows_sandbox::decode_bytes;
|
||||
use akode_windows_sandbox::encode_bytes;
|
||||
use akode_windows_sandbox::get_current_token_for_restriction;
|
||||
use akode_windows_sandbox::hide_current_user_profile_dir;
|
||||
use akode_windows_sandbox::log_note;
|
||||
use akode_windows_sandbox::read_frame;
|
||||
use akode_windows_sandbox::read_handle_loop;
|
||||
use akode_windows_sandbox::spawn_process_with_pipes;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::token_mode_for_permission_profile;
|
||||
use akode_windows_sandbox::write_frame;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::File;
|
||||
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 std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
|
||||
use windows_sys::Win32::Foundation::GetLastError;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
|
||||
use windows_sys::Win32::System::Console::COORD;
|
||||
use windows_sys::Win32::System::Console::HPCON;
|
||||
use windows_sys::Win32::System::Console::ResizePseudoConsole;
|
||||
use windows_sys::Win32::System::Threading::GetExitCodeProcess;
|
||||
use windows_sys::Win32::System::Threading::GetProcessId;
|
||||
use windows_sys::Win32::System::Threading::INFINITE;
|
||||
use windows_sys::Win32::System::Threading::MUTEX_ALL_ACCESS;
|
||||
use windows_sys::Win32::System::Threading::OpenMutexW;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
|
||||
const READ_ACL_MUTEX_NAME: &str = "Local\\CodexSandboxReadAcl";
|
||||
const TERMINATION_WAIT_MS: u32 = 5_000;
|
||||
const WAIT_TIMEOUT: u32 = 0x0000_0102;
|
||||
|
||||
struct IpcSpawnedProcess {
|
||||
log_dir: PathBuf,
|
||||
pi: PROCESS_INFORMATION,
|
||||
job: Arc<JobObject>,
|
||||
stdout_handle: HANDLE,
|
||||
stderr_handle: HANDLE,
|
||||
stdin_handle: Option<HANDLE>,
|
||||
conpty_owner: Option<akode_windows_sandbox::ConptyInstance>,
|
||||
hpc_handle: Option<HPCON>,
|
||||
_pipe_handles: Option<PipeSpawnHandles>,
|
||||
}
|
||||
|
||||
struct NonOwningProcessHandle(HANDLE);
|
||||
|
||||
// SAFETY: Process handles are opaque process-wide tokens that may be used from
|
||||
// any thread. This wrapper does not own the handle or extend its lifetime.
|
||||
unsafe impl Send for NonOwningProcessHandle {}
|
||||
|
||||
/// Small RAII wrapper for raw Win32 handles.
|
||||
///
|
||||
/// The elevated runner has a few early-return paths where we acquire a token, job, or pipe
|
||||
/// handle and then may fail while preparing the child. Keeping those handles in a guard makes
|
||||
/// the error paths read more directly and closes the gaps that were previously leaking them.
|
||||
struct OwnedWinHandle(HANDLE);
|
||||
|
||||
impl OwnedWinHandle {
|
||||
fn new(handle: HANDLE) -> Self {
|
||||
Self(handle)
|
||||
}
|
||||
|
||||
fn raw(&self) -> HANDLE {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn into_raw(mut self) -> HANDLE {
|
||||
// Transfer ownership to the caller. After this point the caller is responsible for
|
||||
// eventually closing the returned HANDLE.
|
||||
let handle = self.0;
|
||||
self.0 = std::ptr::null_mut();
|
||||
handle
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnedWinHandle {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE {
|
||||
unsafe {
|
||||
CloseHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a named pipe created by the parent process.
|
||||
fn open_pipe(name: &str, access: u32) -> Result<HANDLE> {
|
||||
let path = to_wide(name);
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
path.as_ptr(),
|
||||
access,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
|
||||
let err = unsafe { GetLastError() };
|
||||
return Err(anyhow::anyhow!("CreateFileW failed for pipe {name}: {err}"));
|
||||
}
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Send an error frame back to the parent process.
|
||||
fn send_error(
|
||||
writer: &Arc<StdMutex<File>>,
|
||||
stage: ErrorStage,
|
||||
windows_error_code: Option<u32>,
|
||||
message: String,
|
||||
) -> Result<()> {
|
||||
let msg = FramedMessage {
|
||||
version: IPC_PROTOCOL_VERSION,
|
||||
message: Message::Error {
|
||||
payload: ErrorPayload {
|
||||
message,
|
||||
stage,
|
||||
windows_error_code,
|
||||
},
|
||||
},
|
||||
};
|
||||
if let Ok(mut guard) = writer.lock() {
|
||||
write_frame(&mut *guard, &msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn windows_error_code(err: &anyhow::Error) -> Option<u32> {
|
||||
err.chain().find_map(|cause| {
|
||||
cause
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(std::io::Error::raw_os_error)
|
||||
.and_then(|code| u32::try_from(code).ok())
|
||||
})
|
||||
}
|
||||
|
||||
/// Read and validate the initial spawn request frame.
|
||||
fn read_spawn_request(reader: &mut File) -> Result<SpawnRequest> {
|
||||
let Some(msg) = read_frame(reader)? else {
|
||||
anyhow::bail!("runner: pipe closed before spawn_request");
|
||||
};
|
||||
if msg.version != IPC_PROTOCOL_VERSION {
|
||||
anyhow::bail!("runner: unsupported protocol version {}", msg.version);
|
||||
}
|
||||
match msg.message {
|
||||
Message::SpawnRequest { payload } => Ok(*payload),
|
||||
other => anyhow::bail!("runner: expected spawn_request, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_acl_mutex_exists() -> Result<bool> {
|
||||
let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));
|
||||
let handle = unsafe { OpenMutexW(MUTEX_ALL_ACCESS, 0, name.as_ptr()) };
|
||||
if handle.is_null() {
|
||||
let err = unsafe { GetLastError() };
|
||||
if err == ERROR_FILE_NOT_FOUND {
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(anyhow::anyhow!("OpenMutexW failed: {err}"));
|
||||
}
|
||||
unsafe {
|
||||
CloseHandle(handle);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Pick an effective CWD, using a junction if the ACL helper is active.
|
||||
fn effective_cwd(req_cwd: &Path, log_dir: Option<&Path>) -> PathBuf {
|
||||
let use_junction = match read_acl_mutex_exists() {
|
||||
Ok(exists) => exists,
|
||||
Err(err) => {
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: failed to probe ACL mutex state: {err}; defaulting to junction cwd"
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
true
|
||||
}
|
||||
};
|
||||
if use_junction {
|
||||
cwd_junction::create_cwd_junction(req_cwd, log_dir).unwrap_or_else(|| req_cwd.to_path_buf())
|
||||
} else {
|
||||
req_cwd.to_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {
|
||||
let log_dir = req.codex_home.clone();
|
||||
hide_current_user_profile_dir(req.codex_home.as_path());
|
||||
let token_mode = token_mode_for_permission_profile(
|
||||
&req.permission_profile,
|
||||
&req.workspace_roots,
|
||||
&req.cwd,
|
||||
&req.env,
|
||||
)
|
||||
.context("resolve permission profile token mode")?;
|
||||
let mut cap_psids: Vec<LocalSid> = Vec::new();
|
||||
for sid in &req.cap_sids {
|
||||
cap_psids.push(
|
||||
LocalSid::from_string(sid)
|
||||
.context("ConvertStringSidToSidW failed for capability SID")?,
|
||||
);
|
||||
}
|
||||
if cap_psids.is_empty() {
|
||||
anyhow::bail!("runner: empty capability SID list");
|
||||
}
|
||||
let network_proxy_restricting_sid = req
|
||||
.network_proxy_restricting_sid
|
||||
.as_deref()
|
||||
.map(LocalSid::from_string)
|
||||
.transpose()
|
||||
.context("ConvertStringSidToSidW failed for network proxy restricting SID")?;
|
||||
|
||||
// The token helpers still take raw SID pointers, but we keep ownership in `LocalSid`
|
||||
// wrappers for as long as possible. That way any failure after SID parsing but before the
|
||||
// child is fully spawned still releases the backing LocalAlloc memory automatically.
|
||||
let cap_psid_ptrs: Vec<*mut _> = cap_psids.iter().map(LocalSid::as_ptr).collect();
|
||||
let additional_restricting_sid_ptrs: Vec<*mut _> = network_proxy_restricting_sid
|
||||
.iter()
|
||||
.map(LocalSid::as_ptr)
|
||||
.collect();
|
||||
let base = OwnedWinHandle::new(unsafe { get_current_token_for_restriction()? });
|
||||
let h_token = unsafe {
|
||||
match token_mode {
|
||||
WindowsSandboxTokenMode::ReadOnlyCapability => {
|
||||
create_readonly_token_with_caps_and_user_from(
|
||||
base.raw(),
|
||||
&cap_psid_ptrs,
|
||||
&additional_restricting_sid_ptrs,
|
||||
)
|
||||
}
|
||||
WindowsSandboxTokenMode::WritableRootsCapability => {
|
||||
create_workspace_write_token_with_caps_and_user_from(
|
||||
base.raw(),
|
||||
&cap_psid_ptrs,
|
||||
&additional_restricting_sid_ptrs,
|
||||
)
|
||||
}
|
||||
}
|
||||
}?;
|
||||
// SAFETY: Both token helpers transfer ownership of the returned handle to the caller.
|
||||
let h_token = unsafe { OwnedHandle::from_raw_handle(h_token) };
|
||||
unsafe {
|
||||
// These ACL adjustments need the raw SID values, but ownership stays with `cap_psids`.
|
||||
// We do not manually `LocalFree` anything here; the wrappers handle every return path.
|
||||
allow_null_device(cap_psid_ptrs[0]);
|
||||
for psid in &cap_psid_ptrs {
|
||||
allow_null_device(*psid);
|
||||
}
|
||||
}
|
||||
|
||||
let effective_cwd = effective_cwd(&req.cwd, Some(log_dir.as_path()));
|
||||
let desktop = LaunchDesktop::open_private(
|
||||
req.private_desktop_name
|
||||
.as_deref()
|
||||
.context("runner: missing parent-owned private desktop")?,
|
||||
)?;
|
||||
|
||||
let mut conpty_owner = None;
|
||||
let mut hpc_handle: Option<HPCON> = None;
|
||||
let mut pipe_handles = None;
|
||||
let (pi, job, stdout_handle, stderr_handle, stdin_handle) = if req.tty {
|
||||
let (pi, mut conpty) = akode_windows_sandbox::spawn_conpty_process_as_user(
|
||||
h_token.as_handle(),
|
||||
&req.command,
|
||||
&effective_cwd,
|
||||
&req.env,
|
||||
desktop,
|
||||
)?;
|
||||
let job = conpty
|
||||
.job()
|
||||
.context("spawned ConPTY is missing its process job")?;
|
||||
hpc_handle = conpty.raw_handle();
|
||||
let input_write = conpty.take_input_write();
|
||||
let output_read = conpty.take_output_read();
|
||||
conpty_owner = Some(conpty);
|
||||
let stdin_handle = if req.stdin_open {
|
||||
Some(input_write)
|
||||
} else {
|
||||
unsafe {
|
||||
CloseHandle(input_write);
|
||||
}
|
||||
None
|
||||
};
|
||||
(
|
||||
pi,
|
||||
job,
|
||||
output_read,
|
||||
windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE,
|
||||
stdin_handle,
|
||||
)
|
||||
} else {
|
||||
let stdin_mode = if req.stdin_open {
|
||||
StdinMode::Open
|
||||
} else {
|
||||
StdinMode::Closed
|
||||
};
|
||||
let spawned_pipes: PipeSpawnHandles = spawn_process_with_pipes(
|
||||
h_token.as_handle(),
|
||||
&req.command,
|
||||
&effective_cwd,
|
||||
&req.env,
|
||||
stdin_mode,
|
||||
StderrMode::Separate,
|
||||
ConsoleMode::NoWindow,
|
||||
desktop,
|
||||
Some(log_dir.as_path()),
|
||||
)?;
|
||||
let pi = spawned_pipes.process;
|
||||
let stdout_handle = spawned_pipes.stdout_read;
|
||||
let stderr_handle = spawned_pipes
|
||||
.stderr_read
|
||||
.unwrap_or(windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE);
|
||||
let stdin_handle = spawned_pipes.stdin_write;
|
||||
let job = spawned_pipes.job();
|
||||
pipe_handles = Some(spawned_pipes);
|
||||
(pi, job, stdout_handle, stderr_handle, stdin_handle)
|
||||
};
|
||||
Ok(IpcSpawnedProcess {
|
||||
log_dir,
|
||||
pi,
|
||||
job,
|
||||
stdout_handle,
|
||||
stderr_handle,
|
||||
stdin_handle,
|
||||
conpty_owner,
|
||||
hpc_handle,
|
||||
_pipe_handles: pipe_handles,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stream stdout/stderr from the child into Output frames.
|
||||
fn spawn_output_reader(
|
||||
writer: Arc<StdMutex<File>>,
|
||||
handle: HANDLE,
|
||||
stream: OutputStream,
|
||||
log_dir: Option<PathBuf>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
// SAFETY: The spawn path transfers this pipe's read end to the reader.
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
read_handle_loop(handle, move |chunk| {
|
||||
let msg = FramedMessage {
|
||||
version: IPC_PROTOCOL_VERSION,
|
||||
message: Message::Output {
|
||||
payload: OutputPayload {
|
||||
data_b64: encode_bytes(chunk),
|
||||
stream,
|
||||
},
|
||||
},
|
||||
};
|
||||
if let Ok(mut guard) = writer.lock()
|
||||
&& let Err(err) = write_frame(&mut *guard, &msg)
|
||||
{
|
||||
log_note(
|
||||
&format!("runner output write failed: {err}"),
|
||||
log_dir.as_deref(),
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn terminate_job_or_process(
|
||||
job: &JobObject,
|
||||
process: &NonOwningProcessHandle,
|
||||
log_dir: Option<&Path>,
|
||||
) {
|
||||
if let Err(job_err) = job.terminate() {
|
||||
log_note(
|
||||
&format!("runner failed to terminate process tree: {job_err}"),
|
||||
log_dir,
|
||||
);
|
||||
if unsafe { TerminateProcess(process.0, 1) } == 0 {
|
||||
log_note(
|
||||
&format!("runner failed to terminate root process: {}", unsafe {
|
||||
GetLastError()
|
||||
}),
|
||||
log_dir,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read stdin/terminate frames and forward to the child process.
|
||||
fn spawn_input_loop(
|
||||
mut reader: File,
|
||||
stdin_handle: Option<HANDLE>,
|
||||
hpc_handle: Arc<StdMutex<Option<HPCON>>>,
|
||||
job: Arc<JobObject>,
|
||||
process: NonOwningProcessHandle,
|
||||
log_dir: Option<PathBuf>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
// SAFETY: The spawn path transfers the pipe's write end to this input loop.
|
||||
let stdin_handle = stdin_handle.map(|handle| unsafe { OwnedHandle::from_raw_handle(handle) });
|
||||
std::thread::spawn(move || {
|
||||
let mut stdin_handle = stdin_handle;
|
||||
loop {
|
||||
let msg = match read_frame(&mut reader) {
|
||||
Ok(Some(v)) => v,
|
||||
Ok(None) | Err(_) => {
|
||||
terminate_job_or_process(&job, &process, log_dir.as_deref());
|
||||
break;
|
||||
}
|
||||
};
|
||||
match msg.message {
|
||||
Message::Stdin { payload } => {
|
||||
let Ok(bytes) = decode_bytes(&payload.data_b64) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(handle) = &stdin_handle {
|
||||
let mut offset = 0usize;
|
||||
// `WriteFile` can report success after consuming only part of the buffer
|
||||
// when the target is a pipe. Treat this like a normal partial write and
|
||||
// keep advancing until every decoded stdin byte has been forwarded.
|
||||
//
|
||||
// If the child closes stdin or the pipe enters an error state, we log
|
||||
// that fact, close our local HANDLE, and stop trying to forward later
|
||||
// `Stdin` frames. That prevents silent truncation while also avoiding an
|
||||
// endless stream of failing writes after the child is already gone.
|
||||
while offset < bytes.len() {
|
||||
let chunk = &bytes[offset..];
|
||||
let chunk_len = chunk.len().min(u32::MAX as usize);
|
||||
let mut written = 0u32;
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::WriteFile(
|
||||
handle.as_raw_handle(),
|
||||
chunk.as_ptr(),
|
||||
chunk_len as u32,
|
||||
&mut written,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
log_note(
|
||||
&format!(
|
||||
"runner stdin write failed after {offset} bytes: {}",
|
||||
unsafe { GetLastError() }
|
||||
),
|
||||
log_dir.as_deref(),
|
||||
);
|
||||
stdin_handle = None;
|
||||
break;
|
||||
}
|
||||
if written == 0 {
|
||||
log_note(
|
||||
"runner stdin write made no progress; closing child stdin",
|
||||
log_dir.as_deref(),
|
||||
);
|
||||
stdin_handle = None;
|
||||
break;
|
||||
}
|
||||
offset += written as usize;
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::CloseStdin { .. } => {
|
||||
drop(stdin_handle.take());
|
||||
}
|
||||
Message::Resize {
|
||||
payload: ResizePayload { rows, cols },
|
||||
} => {
|
||||
if let Ok(guard) = hpc_handle.lock()
|
||||
&& let Some(hpc) = guard.as_ref()
|
||||
{
|
||||
unsafe {
|
||||
let _ = ResizePseudoConsole(
|
||||
*hpc,
|
||||
COORD {
|
||||
X: cols as i16,
|
||||
Y: rows as i16,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::Terminate { .. } => {
|
||||
terminate_job_or_process(&job, &process, log_dir.as_deref());
|
||||
}
|
||||
Message::SpawnRequest { .. } => {}
|
||||
Message::SpawnReady { .. } => {}
|
||||
Message::Output { .. } => {}
|
||||
Message::Exit { .. } => {}
|
||||
Message::Error { .. } => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Entry point for the Windows command runner process.
|
||||
pub fn main() -> Result<()> {
|
||||
let mut pipe_in = None;
|
||||
let mut pipe_out = None;
|
||||
for arg in std::env::args().skip(1) {
|
||||
if let Some(rest) = arg.strip_prefix("--pipe-in=") {
|
||||
pipe_in = Some(rest.to_string());
|
||||
} else if let Some(rest) = arg.strip_prefix("--pipe-out=") {
|
||||
pipe_out = Some(rest.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let Some(pipe_in) = pipe_in else {
|
||||
anyhow::bail!("runner: no pipe-in provided");
|
||||
};
|
||||
let Some(pipe_out) = pipe_out else {
|
||||
anyhow::bail!("runner: no pipe-out provided");
|
||||
};
|
||||
|
||||
// Open both pipe ends under guards first so a failure on the second open cannot leak the
|
||||
// first HANDLE. Only after both opens succeed do we transfer ownership into `File`, which
|
||||
// then becomes responsible for closing them.
|
||||
let h_pipe_in = OwnedWinHandle::new(open_pipe(&pipe_in, FILE_GENERIC_READ)?);
|
||||
let h_pipe_out = OwnedWinHandle::new(open_pipe(&pipe_out, FILE_GENERIC_WRITE)?);
|
||||
let mut pipe_read = unsafe { File::from_raw_handle(h_pipe_in.into_raw() as _) };
|
||||
let pipe_write = Arc::new(StdMutex::new(unsafe {
|
||||
File::from_raw_handle(h_pipe_out.into_raw() as _)
|
||||
}));
|
||||
|
||||
let req = match read_spawn_request(&mut pipe_read) {
|
||||
Ok(v) => v,
|
||||
Err(err) => {
|
||||
let _ = send_error(
|
||||
&pipe_write,
|
||||
ErrorStage::ReadSpawnRequest,
|
||||
/*windows_error_code*/ None,
|
||||
err.to_string(),
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let ipc_spawn = match spawn_ipc_process(&req) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
let _ = send_error(
|
||||
&pipe_write,
|
||||
ErrorStage::SpawnChild,
|
||||
windows_error_code(&err),
|
||||
err.to_string(),
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let log_dir = Some(ipc_spawn.log_dir.as_path());
|
||||
let pi = ipc_spawn.pi;
|
||||
let stdout_handle = ipc_spawn.stdout_handle;
|
||||
let stderr_handle = ipc_spawn.stderr_handle;
|
||||
let job = Arc::clone(&ipc_spawn.job);
|
||||
let mut conpty_owner = ipc_spawn.conpty_owner;
|
||||
let stdin_handle = ipc_spawn.stdin_handle;
|
||||
let hpc_handle = Arc::new(StdMutex::new(ipc_spawn.hpc_handle));
|
||||
|
||||
let msg = FramedMessage {
|
||||
version: IPC_PROTOCOL_VERSION,
|
||||
message: Message::SpawnReady {
|
||||
payload: SpawnReady {
|
||||
process_id: unsafe { GetProcessId(pi.hProcess) },
|
||||
},
|
||||
},
|
||||
};
|
||||
if let Err(err) = if let Ok(mut guard) = pipe_write.lock() {
|
||||
write_frame(&mut *guard, &msg)
|
||||
} else {
|
||||
anyhow::bail!("runner spawn_ready write failed: pipe_write lock poisoned");
|
||||
} {
|
||||
let _ = send_error(
|
||||
&pipe_write,
|
||||
ErrorStage::WriteSpawnReady,
|
||||
/*windows_error_code*/ None,
|
||||
err.to_string(),
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
let log_dir_owned = log_dir.map(Path::to_path_buf);
|
||||
let out_thread = spawn_output_reader(
|
||||
Arc::clone(&pipe_write),
|
||||
stdout_handle,
|
||||
OutputStream::Stdout,
|
||||
log_dir_owned.clone(),
|
||||
);
|
||||
let err_thread = if stderr_handle != windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
|
||||
Some(spawn_output_reader(
|
||||
Arc::clone(&pipe_write),
|
||||
stderr_handle,
|
||||
OutputStream::Stderr,
|
||||
log_dir_owned.clone(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let _input_thread = spawn_input_loop(
|
||||
pipe_read,
|
||||
stdin_handle,
|
||||
Arc::clone(&hpc_handle),
|
||||
Arc::clone(&job),
|
||||
NonOwningProcessHandle(pi.hProcess),
|
||||
log_dir_owned,
|
||||
);
|
||||
|
||||
let timeout = req.timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE);
|
||||
let wait_res = unsafe { WaitForSingleObject(pi.hProcess, timeout) };
|
||||
let timed_out = wait_res == WAIT_TIMEOUT;
|
||||
let child_stopped = if timed_out {
|
||||
terminate_job_or_process(&job, &NonOwningProcessHandle(pi.hProcess), log_dir);
|
||||
let termination_wait = unsafe { WaitForSingleObject(pi.hProcess, TERMINATION_WAIT_MS) };
|
||||
if termination_wait == WAIT_TIMEOUT {
|
||||
log_note(
|
||||
"runner root process did not exit after termination",
|
||||
log_dir,
|
||||
);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
if let Err(err) = job.preserve_descendants() {
|
||||
log_note(
|
||||
&format!("runner failed to preserve descendants after root exit: {err}"),
|
||||
log_dir,
|
||||
);
|
||||
}
|
||||
true
|
||||
};
|
||||
|
||||
let exit_code: i32;
|
||||
unsafe {
|
||||
if timed_out {
|
||||
exit_code = 128 + 64;
|
||||
} else {
|
||||
let mut raw_exit: u32 = 1;
|
||||
GetExitCodeProcess(pi.hProcess, &mut raw_exit);
|
||||
exit_code = raw_exit as i32;
|
||||
}
|
||||
if !pi.hThread.is_null() {
|
||||
CloseHandle(pi.hThread);
|
||||
}
|
||||
if !pi.hProcess.is_null() {
|
||||
CloseHandle(pi.hProcess);
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(mut guard) = hpc_handle.lock() {
|
||||
let _ = guard.take();
|
||||
}
|
||||
drop(conpty_owner.take());
|
||||
|
||||
if child_stopped {
|
||||
if out_thread.join().is_err() {
|
||||
log_note("runner stdout reader thread panicked", log_dir);
|
||||
}
|
||||
if let Some(thread) = err_thread
|
||||
&& thread.join().is_err()
|
||||
{
|
||||
log_note("runner stderr reader thread panicked", log_dir);
|
||||
}
|
||||
}
|
||||
|
||||
let exit_msg = FramedMessage {
|
||||
version: IPC_PROTOCOL_VERSION,
|
||||
message: Message::Exit {
|
||||
payload: ExitPayload {
|
||||
exit_code,
|
||||
timed_out,
|
||||
},
|
||||
},
|
||||
};
|
||||
if let Ok(mut guard) = pipe_write.lock()
|
||||
&& let Err(err) = write_frame(&mut *guard, &exit_msg)
|
||||
{
|
||||
log_note(&format!("runner exit write failed: {err}"), log_dir);
|
||||
}
|
||||
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
use akode_windows_sandbox::log_note;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::Hash;
|
||||
use std::hash::Hasher;
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
|
||||
|
||||
fn junction_name_for_path(path: &Path) -> String {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
path.to_string_lossy().hash(&mut hasher);
|
||||
format!("{:x}", hasher.finish())
|
||||
}
|
||||
|
||||
fn junction_root_for_userprofile(userprofile: &str) -> PathBuf {
|
||||
PathBuf::from(userprofile)
|
||||
.join(".akode")
|
||||
.join(".sandbox")
|
||||
.join("cwd")
|
||||
}
|
||||
|
||||
pub fn create_cwd_junction(requested_cwd: &Path, log_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
let userprofile = std::env::var("USERPROFILE").ok()?;
|
||||
let junction_root = junction_root_for_userprofile(&userprofile);
|
||||
if let Err(err) = std::fs::create_dir_all(&junction_root) {
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: failed to create {}: {err}",
|
||||
junction_root.display()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let junction_path = junction_root.join(junction_name_for_path(requested_cwd));
|
||||
if junction_path.exists() {
|
||||
// Reuse an existing junction if it looks like a reparse point; this keeps the hot path
|
||||
// cheap and avoids repeatedly shelling out to mklink.
|
||||
match std::fs::symlink_metadata(&junction_path) {
|
||||
Ok(md) if (md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT) != 0 => {
|
||||
log_note(
|
||||
&format!("junction: reusing existing {}", junction_path.display()),
|
||||
log_dir,
|
||||
);
|
||||
return Some(junction_path);
|
||||
}
|
||||
Ok(_) => {
|
||||
// Unexpected: something else exists at this path (regular directory/file). We'll
|
||||
// try to remove it if possible and recreate the junction.
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: existing path is not a reparse point, recreating {}",
|
||||
junction_path.display()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: failed to stat existing {}: {err}",
|
||||
junction_path.display()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(err) = std::fs::remove_dir(&junction_path) {
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: failed to remove existing {}: {err}",
|
||||
junction_path.display()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
let link = junction_path.to_string_lossy().to_string();
|
||||
let target = requested_cwd.to_string_lossy().to_string();
|
||||
|
||||
// Use `cmd /c` so we can call `mklink` (a cmd builtin). We must quote paths so CWDs
|
||||
// containing spaces work reliably.
|
||||
//
|
||||
// IMPORTANT: `std::process::Command::args()` will apply Windows quoting/escaping rules when
|
||||
// constructing the command line. Passing a single argument that itself contains quotes can
|
||||
// confuse `cmd.exe` and cause mklink to fail with "syntax is incorrect". We avoid that by
|
||||
// using `raw_arg` to pass the tokens exactly as `cmd.exe` expects to parse them.
|
||||
//
|
||||
// Paths cannot contain quotes on Windows, so no extra escaping is needed here.
|
||||
let link_quoted = format!("\"{link}\"");
|
||||
let target_quoted = format!("\"{target}\"");
|
||||
log_note(
|
||||
&format!("junction: creating via cmd /c mklink /J {link_quoted} {target_quoted}"),
|
||||
log_dir,
|
||||
);
|
||||
let output = match akode_utils_process::background_command("cmd")
|
||||
.raw_arg("/c")
|
||||
.raw_arg("mklink")
|
||||
.raw_arg("/J")
|
||||
.raw_arg(&link_quoted)
|
||||
.raw_arg(&target_quoted)
|
||||
.output()
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
log_note(&format!("junction: mklink failed to run: {err}"), log_dir);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if output.status.success() && junction_path.exists() {
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: created {} -> {}",
|
||||
junction_path.display(),
|
||||
requested_cwd.display()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
return Some(junction_path);
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log_note(
|
||||
&format!(
|
||||
"junction: mklink failed status={:?} stdout={} stderr={}",
|
||||
output.status,
|
||||
stdout.trim(),
|
||||
stderr.trim()
|
||||
),
|
||||
log_dir,
|
||||
);
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use akode_utils_pty::JobObject;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
|
||||
use super::NonOwningProcessHandle;
|
||||
use super::spawn_input_loop;
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnected_control_pipe_terminates_elevated_helper_and_descendants() -> anyhow::Result<()>
|
||||
{
|
||||
let mut command = Command::new("python");
|
||||
command
|
||||
.args([
|
||||
"-u",
|
||||
"-c",
|
||||
"import subprocess,sys; child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']); print(child.pid,flush=True); child.wait()",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
|
||||
let job = Arc::new(JobObject::create_without_breakaway()?);
|
||||
let mut helper = job.spawn_contained(&mut command)?;
|
||||
let stdout = helper.stdout.take().context("helper stdout")?;
|
||||
let mut stdout = BufReader::new(stdout);
|
||||
let mut descendant_pid = String::new();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
stdout.read_line(&mut descendant_pid),
|
||||
)
|
||||
.await??;
|
||||
let descendant_pid = descendant_pid.trim().parse()?;
|
||||
let descendant = unsafe {
|
||||
OpenProcess(
|
||||
PROCESS_SYNCHRONIZE,
|
||||
/*bInheritHandle*/ 0,
|
||||
descendant_pid,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(!descendant.is_null(), "failed to open sandbox descendant");
|
||||
let descendant = unsafe { OwnedHandle::from_raw_handle(descendant as _) };
|
||||
let process = helper.raw_handle().context("helper process handle")?;
|
||||
|
||||
let input_loop = spawn_input_loop(
|
||||
tempfile::tempfile()?,
|
||||
/*stdin_handle*/ None,
|
||||
Arc::new(Mutex::new(None)),
|
||||
Arc::clone(&job),
|
||||
NonOwningProcessHandle(process),
|
||||
/*log_dir*/ None,
|
||||
);
|
||||
input_loop
|
||||
.join()
|
||||
.expect("elevated runner input loop should stop after pipe disconnect");
|
||||
|
||||
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), helper.wait())
|
||||
.await
|
||||
.context("elevated helper survived control-pipe disconnect")??;
|
||||
anyhow::ensure!(!status.success(), "elevated helper unexpectedly succeeded");
|
||||
let descendant_status = unsafe {
|
||||
WaitForSingleObject(
|
||||
descendant.as_raw_handle() as _,
|
||||
/*dwMilliseconds*/ 2_000,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(
|
||||
descendant_status == WAIT_OBJECT_0,
|
||||
"elevated descendant survived control-pipe disconnect"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Keep the ACL probe independent of test-harness startup, which writes AKODE_HOME.
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn main() {
|
||||
win::main();
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn main() {
|
||||
panic!("akode-windows-managed-deny-probe is Windows-only");
|
||||
}
|
||||
101
akode-rs/windows-sandbox-rs/src/bin/managed_deny_probe/win.rs
Normal file
101
akode-rs/windows-sandbox-rs/src/bin/managed_deny_probe/win.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use std::ffi::c_void;
|
||||
use std::io::Write as _;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
#[link_name = "LoadLibraryW"]
|
||||
fn load_library_w(file_name: *const u16) -> *mut c_void;
|
||||
#[link_name = "FreeLibrary"]
|
||||
fn free_library(module: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
fn load_library(path: &Path) -> std::io::Result<()> {
|
||||
let wide_path: Vec<u16> = path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
// SAFETY: `wide_path` is NUL-terminated and remains alive for the call.
|
||||
let module = unsafe { load_library_w(wide_path.as_ptr()) };
|
||||
if module.is_null() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: `module` is a non-null handle returned by `LoadLibraryW` above.
|
||||
if unsafe { free_library(module) } == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn access_was_denied(err: &std::io::Error) -> bool {
|
||||
err.kind() == std::io::ErrorKind::PermissionDenied || err.raw_os_error() == Some(5)
|
||||
}
|
||||
|
||||
fn probe_path(key: &str) -> PathBuf {
|
||||
let Some(value) = std::env::var_os(key) else {
|
||||
eprintln!("managed deny probe is missing {key}");
|
||||
probe_exit(/*code*/ 21);
|
||||
};
|
||||
PathBuf::from(value)
|
||||
}
|
||||
|
||||
fn probe_exit(code: i32) -> ! {
|
||||
let _ = std::io::stdout().flush();
|
||||
let _ = std::io::stderr().flush();
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
pub(super) fn main() {
|
||||
let allowed_text = probe_path("AKODE_WINDOWS_ALLOWED_TEXT");
|
||||
let denied_text = probe_path("AKODE_WINDOWS_DENIED_TEXT");
|
||||
let allowed_module = probe_path("AKODE_WINDOWS_ALLOWED_MODULE");
|
||||
let denied_module = probe_path("AKODE_WINDOWS_DENIED_MODULE");
|
||||
|
||||
match std::fs::read_to_string(&allowed_text) {
|
||||
Ok(contents) if contents.trim() == "ALLOW-CONTROL" => println!("allowed-read:OK"),
|
||||
Ok(_) => {
|
||||
eprintln!("allowed read returned unexpected contents");
|
||||
probe_exit(/*code*/ 21);
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("allowed read failed: {err}");
|
||||
probe_exit(/*code*/ 21);
|
||||
}
|
||||
}
|
||||
if let Err(err) = load_library(&allowed_module) {
|
||||
eprintln!("allowed import failed: {err}");
|
||||
probe_exit(/*code*/ 21);
|
||||
}
|
||||
println!("allowed-import:OK");
|
||||
|
||||
let mut failures = 0;
|
||||
match std::fs::read(&denied_text) {
|
||||
Ok(_) => {
|
||||
println!("denied-read:UNEXPECTED_SUCCESS");
|
||||
failures += 1;
|
||||
}
|
||||
Err(err) if access_was_denied(&err) => println!("denied-read:DENIED"),
|
||||
Err(err) => {
|
||||
eprintln!("denied read failed for a non-access reason: {err}");
|
||||
probe_exit(/*code*/ 21);
|
||||
}
|
||||
}
|
||||
match load_library(&denied_module) {
|
||||
Ok(()) => {
|
||||
println!("denied-import:UNEXPECTED_SUCCESS");
|
||||
failures += 1;
|
||||
}
|
||||
Err(err) if access_was_denied(&err) => println!("denied-import:DENIED"),
|
||||
Err(err) => {
|
||||
eprintln!("denied import failed for a non-access reason: {err}");
|
||||
probe_exit(/*code*/ 21);
|
||||
}
|
||||
}
|
||||
|
||||
if failures != 0 {
|
||||
probe_exit(/*code*/ 20);
|
||||
}
|
||||
}
|
||||
9
akode-rs/windows-sandbox-rs/src/bin/setup_main/main.rs
Normal file
9
akode-rs/windows-sandbox-rs/src/bin/setup_main/main.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
#[cfg(target_os = "windows")]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
akode_windows_sandbox::setup_helper_main()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn main() {
|
||||
panic!("akode-windows-sandbox-setup is Windows-only");
|
||||
}
|
||||
Reference in New Issue
Block a user