Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

6
akode-rs/uds/BUILD.bazel Normal file
View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "uds",
crate_name = "akode_uds",
)

34
akode-rs/uds/Cargo.toml Normal file
View File

@@ -0,0 +1,34 @@
[package]
name = "akode-uds"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "akode_uds"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
tokio = { workspace = true, features = ["fs", "net", "rt"] }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
[target.'cfg(windows)'.dependencies]
async-io = { workspace = true }
tokio-util = { workspace = true, features = ["compat"] }
uds_windows = { workspace = true }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemServices", "Win32_Networking_WinSock", "Win32_System_IO"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"io-util",
"macros",
"rt-multi-thread",
] }

View File

@@ -0,0 +1,39 @@
//! The host-local rendezvous root for privileged app-server RPC sockets.
//!
//! Every listener uses this root, which sandboxes hide even before a daemon
//! starts. It must not depend on HOME, TMPDIR, AKODE_HOME, or command settings.
use std::fs;
use std::io;
use std::os::unix::fs::DirBuilderExt;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
/// Returns the fixed executor-local directory that every sandbox must hide.
pub fn shared_daemon_socket_directory() -> io::Result<PathBuf> {
// Resolve the system alias /tmp -> /private/tmp on macOS.
let temporary_root = fs::canonicalize("/tmp")?;
let uid = unsafe { libc::geteuid() };
Ok(temporary_root.join(format!("codex-daemon-{uid}")))
}
/// Creates the reserved directory, rejecting symlinks and unsafe existing owners or modes.
pub fn prepare_shared_daemon_socket_directory() -> io::Result<PathBuf> {
let directory = shared_daemon_socket_directory()?;
match fs::DirBuilder::new().mode(0o700).create(&directory) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error),
}
let metadata = fs::symlink_metadata(&directory)?;
if !metadata.is_dir()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o777 != 0o700
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"app-server socket directory must be a user-owned directory with mode 0700",
));
}
Ok(directory)
}

375
akode-rs/uds/src/lib.rs Normal file
View File

@@ -0,0 +1,375 @@
//! Cross-platform async Unix domain socket helpers.
#[cfg(unix)]
mod daemon_directory;
#[cfg(unix)]
pub use daemon_directory::prepare_shared_daemon_socket_directory;
#[cfg(unix)]
pub use daemon_directory::shared_daemon_socket_directory;
use std::io::Result as IoResult;
use std::path::Path;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::io::ReadBuf;
/// Creates `socket_dir` if needed and restricts it to the current user as
/// supported by the platform (0700 on Unix, a protected user-only DACL on Windows).
/// Windows rejects existing directories unless they already have that owner and DACL;
/// changing permissions cannot revoke access held through preexisting handles.
pub async fn prepare_private_socket_directory(socket_dir: impl AsRef<Path>) -> IoResult<()> {
platform::prepare_private_socket_directory(socket_dir.as_ref()).await
}
/// Returns whether `socket_path` points at a stale Unix socket rendezvous path.
///
/// On Unix this checks the file type. On Windows, `uds_windows` represents the
/// rendezvous as a regular path, so existence is the only useful stale-path
/// signal available.
pub async fn is_stale_socket_path(socket_path: impl AsRef<Path>) -> IoResult<bool> {
platform::is_stale_socket_path(socket_path.as_ref()).await
}
/// Async Unix domain socket listener.
pub struct UnixListener {
inner: platform::Listener,
}
impl UnixListener {
/// Binds a new listener at `socket_path`.
pub async fn bind(socket_path: impl AsRef<Path>) -> IoResult<Self> {
platform::bind_listener(socket_path.as_ref())
.await
.map(|inner| Self { inner })
}
/// Accepts the next incoming stream.
pub async fn accept(&mut self) -> IoResult<UnixStream> {
self.inner.accept().await.map(|inner| UnixStream { inner })
}
}
/// Async Unix domain socket stream.
pub struct UnixStream {
inner: platform::Stream,
}
impl UnixStream {
/// Requires the Windows peer to belong to the current user, with neither
/// process elevated. Call before sending any application data.
#[cfg(windows)]
pub fn ensure_non_elevated_peer(&self) -> IoResult<()> {
self.inner.ensure_non_elevated_peer()
}
/// Connects to `socket_path`.
pub async fn connect(socket_path: impl AsRef<Path>) -> IoResult<Self> {
platform::connect_stream(socket_path.as_ref())
.await
.map(|inner| Self { inner })
}
}
impl AsyncRead for UnixStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<IoResult<()>> {
Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
}
}
impl AsyncWrite for UnixStream {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
}
}
#[cfg(unix)]
mod platform {
use std::io;
use std::io::ErrorKind;
use std::io::Result as IoResult;
use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use tokio::fs;
use tokio::net::UnixListener;
use tokio::net::UnixStream;
/// Owner-only access keeps the control socket directory private while
/// preserving owner traversal and socket path creation.
const SOCKET_DIR_MODE: u32 = 0o700;
const SOCKET_DIR_PERMISSION_BITS: u32 = 0o777;
pub(super) type Stream = UnixStream;
pub(super) struct Listener(UnixListener);
pub(super) async fn prepare_private_socket_directory(socket_dir: &Path) -> IoResult<()> {
let mut dir_builder = fs::DirBuilder::new();
dir_builder.mode(SOCKET_DIR_MODE);
match dir_builder.create(socket_dir).await {
Ok(()) => return Ok(()),
Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
Err(err) => return Err(err),
}
let metadata = fs::symlink_metadata(socket_dir).await?;
if !metadata.is_dir() {
return Err(io::Error::new(
ErrorKind::AlreadyExists,
format!(
"socket directory path exists and is not a directory: {}",
socket_dir.display()
),
));
}
let permissions = metadata.permissions();
// The SSH-over-UDS control socket is reachable by path, so the
// rendezvous directory must be owner-traversable while denying
// group/other access; exact 0700 fixes insecure modes and unusable
// owner-only modes like 0600.
if permissions.mode() & SOCKET_DIR_PERMISSION_BITS != SOCKET_DIR_MODE {
fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(SOCKET_DIR_MODE))
.await?;
}
Ok(())
}
pub(super) async fn bind_listener(socket_path: &Path) -> IoResult<Listener> {
UnixListener::bind(socket_path).map(Listener)
}
impl Listener {
pub(super) async fn accept(&mut self) -> IoResult<Stream> {
self.0.accept().await.map(|(stream, _addr)| stream)
}
}
pub(super) async fn connect_stream(socket_path: &Path) -> IoResult<Stream> {
match UnixStream::connect(socket_path).await {
Err(err) if err.kind() == ErrorKind::InvalidInput => {
// The advertised path may exceed sun_path even when its symlink
// target is a short socket path. Resolve it before retrying.
UnixStream::connect(fs::canonicalize(socket_path).await?).await
}
result => result,
}
}
pub(super) async fn is_stale_socket_path(socket_path: &Path) -> IoResult<bool> {
Ok(fs::symlink_metadata(socket_path)
.await?
.file_type()
.is_socket())
}
}
#[cfg(windows)]
mod platform {
use std::io;
use std::io::Result as IoResult;
use std::net::Shutdown;
use std::ops::Deref;
use std::os::windows::io::AsRawSocket;
use std::os::windows::io::AsSocket;
use std::os::windows::io::BorrowedSocket;
use std::path::Path;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use std::task::ready;
use async_io::Async;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::io::ReadBuf;
use tokio::task;
use tokio_util::compat::Compat;
use tokio_util::compat::FuturesAsyncReadCompatExt;
pub(super) struct Stream(Compat<Async<WindowsUnixStream>>);
impl Stream {
pub(super) fn ensure_non_elevated_peer(&self) -> IoResult<()> {
crate::windows_peer::ensure_non_elevated_peer(
self.0.get_ref().get_ref().as_raw_socket(),
)
}
}
pub(super) async fn prepare_private_socket_directory(socket_dir: &Path) -> IoResult<()> {
let socket_dir = socket_dir.to_path_buf();
spawn_blocking_io(move || crate::windows_security::prepare_private_directory(&socket_dir))
.await
}
pub(super) struct Listener(Async<WindowsUnixListener>);
pub(super) async fn bind_listener(socket_path: &Path) -> IoResult<Listener> {
let socket_path = socket_path.to_path_buf();
let listener =
spawn_blocking_io(move || uds_windows::UnixListener::bind(socket_path)).await?;
Async::new(WindowsUnixListener::from(listener)).map(Listener)
}
impl Listener {
pub(super) async fn accept(&mut self) -> IoResult<Stream> {
let (stream, _addr) = self.0.read_with(|listener| listener.accept()).await?;
Async::new(WindowsUnixStream::from(stream))
.map(FuturesAsyncReadCompatExt::compat)
.map(Stream)
}
}
pub(super) async fn connect_stream(socket_path: &Path) -> IoResult<Stream> {
let socket_path = socket_path.to_path_buf();
let stream =
spawn_blocking_io(move || uds_windows::UnixStream::connect(socket_path)).await?;
Async::new(WindowsUnixStream::from(stream))
.map(FuturesAsyncReadCompatExt::compat)
.map(Stream)
}
pub(super) async fn is_stale_socket_path(socket_path: &Path) -> IoResult<bool> {
tokio::fs::try_exists(socket_path).await
}
async fn spawn_blocking_io<T>(
operation: impl FnOnce() -> IoResult<T> + Send + 'static,
) -> IoResult<T>
where
T: Send + 'static,
{
task::spawn_blocking(operation)
.await
.map_err(|err| io::Error::other(format!("blocking socket task failed: {err}")))?
}
pub(super) struct WindowsUnixListener(uds_windows::UnixListener);
impl From<uds_windows::UnixListener> for WindowsUnixListener {
fn from(listener: uds_windows::UnixListener) -> Self {
Self(listener)
}
}
impl Deref for WindowsUnixListener {
type Target = uds_windows::UnixListener;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsSocket for WindowsUnixListener {
fn as_socket(&self) -> BorrowedSocket<'_> {
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
}
}
pub(super) struct WindowsUnixStream(uds_windows::UnixStream);
impl From<uds_windows::UnixStream> for WindowsUnixStream {
fn from(stream: uds_windows::UnixStream) -> Self {
Self(stream)
}
}
impl Deref for WindowsUnixStream {
type Target = uds_windows::UnixStream;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsSocket for WindowsUnixStream {
fn as_socket(&self) -> BorrowedSocket<'_> {
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
}
}
impl io::Read for WindowsUnixStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
io::Read::read(&mut self.0, buf)
}
}
impl io::Write for WindowsUnixStream {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
io::Write::write(&mut self.0, buf)
}
fn flush(&mut self) -> IoResult<()> {
io::Write::flush(&mut self.0)
}
}
impl AsyncRead for Stream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<IoResult<()>> {
Pin::new(&mut self.get_mut().0).poll_read(cx, buf)
}
}
impl AsyncWrite for Stream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<IoResult<usize>> {
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Pin::new(&mut self.get_mut().0).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
let stream = &mut self.get_mut().0;
ready!(Pin::new(&mut *stream).poll_flush(cx))?;
// `Compat<Async<_>>` maps shutdown to `poll_close()`, which only
// flushes for `async_io::Async`; call the socket shutdown directly.
stream.get_ref().get_ref().shutdown(Shutdown::Write)?;
Poll::Ready(Ok(()))
}
}
unsafe impl async_io::IoSafe for WindowsUnixListener {}
unsafe impl async_io::IoSafe for WindowsUnixStream {}
}
#[cfg(test)]
mod lib_tests;
#[cfg(windows)]
mod windows_security;
#[cfg(windows)]
mod windows_socket_validation;
#[cfg(windows)]
pub use windows_socket_validation::validate_private_socket_path;
#[cfg(windows)]
mod windows_peer;

View File

@@ -0,0 +1,307 @@
use std::io::ErrorKind;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use super::*;
#[cfg(windows)]
#[tokio::test]
async fn private_directory_rejects_volume_roots() {
// A nonexistent volume keeps this regression safe even if root validation breaks.
let root = Path::new(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\");
assert_eq!(
prepare_private_socket_directory(root)
.await
.unwrap_err()
.kind(),
ErrorKind::InvalidInput,
);
}
#[cfg(windows)]
#[tokio::test]
async fn private_directory_rejects_junctions() {
let temp = tempfile::TempDir::new().expect("temp directory");
let target = temp.path().join("target");
let junction = temp.path().join("junction");
std::fs::create_dir(&target).expect("target");
let output = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference = 'Stop'; New-Item -ItemType Junction -Path $env:AKODE_TEST_LINK -Target $env:AKODE_TEST_TARGET | Out-Null"])
.env("AKODE_TEST_LINK", &junction)
.env("AKODE_TEST_TARGET", &target)
.output().expect("create junction");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
prepare_private_socket_directory(&junction)
.await
.unwrap_err()
.kind(),
ErrorKind::PermissionDenied,
);
assert_eq!(
validate_private_socket_path(&junction.join("socket"))
.unwrap_err()
.kind(),
ErrorKind::PermissionDenied,
);
}
#[cfg(windows)]
#[tokio::test]
async fn socket_validation_pins_private_directory_without_creating_missing_paths() {
let temp = tempfile::TempDir::new().expect("temp directory");
let directory = temp.path().join("private");
let socket_path = directory.join("socket");
assert!(validate_private_socket_path(&socket_path).is_err());
assert!(!directory.exists());
prepare_private_socket_directory(&directory).await.unwrap();
let (_validated_path, _guard) = validate_private_socket_path(&socket_path).unwrap();
assert!(std::fs::rename(&directory, temp.path().join("moved")).is_err());
}
#[cfg(windows)]
#[tokio::test]
async fn socket_validation_rejects_broad_acl_without_repairing_it() {
let temp = tempfile::TempDir::new().expect("temp directory");
let directory = temp.path().join("private");
prepare_private_socket_directory(&directory).await.unwrap();
let inspect = |script: &str| {
let output = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.env("AKODE_TEST_DIRECTORY", &directory)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
output.stdout
};
let before = inspect(
r#"
$ErrorActionPreference = 'Stop'
$acl = Get-Acl -LiteralPath $env:AKODE_TEST_DIRECTORY
$everyone = [System.Security.Principal.SecurityIdentifier]::new('S-1-1-0')
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($everyone, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
Set-Acl -LiteralPath $env:AKODE_TEST_DIRECTORY -AclObject $acl
(Get-Acl -LiteralPath $env:AKODE_TEST_DIRECTORY).Sddl
"#,
);
assert_eq!(
validate_private_socket_path(&directory.join("socket"))
.unwrap_err()
.kind(),
ErrorKind::PermissionDenied,
);
assert_eq!(
prepare_private_socket_directory(&directory)
.await
.unwrap_err()
.kind(),
ErrorKind::PermissionDenied,
);
assert_eq!(
before,
inspect(
"$ErrorActionPreference = 'Stop'; (Get-Acl -LiteralPath $env:AKODE_TEST_DIRECTORY).Sddl"
)
);
}
#[cfg(windows)]
#[tokio::test]
async fn private_directory_supports_extended_length_paths() {
let temp = tempfile::TempDir::new().expect("temp directory");
let directory = temp.path().join("a".repeat(150)).join("b".repeat(150));
prepare_private_socket_directory(&directory)
.await
.expect("create long private directory");
prepare_private_socket_directory(&directory)
.await
.expect("validate long private directory");
assert!(directory.is_dir());
}
#[cfg(windows)]
#[tokio::test]
async fn private_directory_acl_is_user_only_and_inherited_by_files() {
let temp = tempfile::TempDir::new().expect("temp directory");
let directory = temp.path().join("private");
// Cover reusing an existing private directory as well as inheriting its DACL.
prepare_private_socket_directory(&directory)
.await
.expect("create user-owned directory");
prepare_private_socket_directory(&directory)
.await
.expect("private directory");
std::fs::write(directory.join("child"), b"").expect("child file");
let _listener = UnixListener::bind(directory.join("socket"))
.await
.expect("private socket");
let output = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", r#"
$ErrorActionPreference = 'Stop'
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$directory = Get-Acl -LiteralPath $env:AKODE_TEST_PRIVATE_DIRECTORY
if (-not $directory.AreAccessRulesProtected) { throw 'directory inherits broad access' }
foreach ($acl in @($directory, (Get-Acl -LiteralPath (Join-Path $env:AKODE_TEST_PRIVATE_DIRECTORY 'child')), (Get-Acl -LiteralPath (Join-Path $env:AKODE_TEST_PRIVATE_DIRECTORY 'socket')))) {
$rules = @($acl.Access)
if ($rules.Count -ne 1) { throw 'unexpected access rules' }
if ($rules[0].IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $sid) { throw 'wrong user' }
if ($rules[0].AccessControlType -ne 'Allow') { throw 'user is denied access' }
}
"#])
.env("AKODE_TEST_PRIVATE_DIRECTORY", &directory)
.output().expect("inspect ACLs");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[tokio::test]
async fn prepare_private_socket_directory_creates_directory() {
let temp_dir = tempfile::TempDir::new().expect("temp dir");
let socket_dir = temp_dir.path().join("app-server-control");
prepare_private_socket_directory(&socket_dir)
.await
.expect("socket dir should be created");
assert!(socket_dir.is_dir());
}
#[cfg(unix)]
#[tokio::test]
async fn prepare_private_socket_directory_sets_existing_permissions_to_owner_only() {
use std::os::unix::fs::PermissionsExt;
let temp_dir = tempfile::TempDir::new().expect("temp dir");
for mode in [0o755, 0o600] {
let socket_dir = temp_dir.path().join(format!("app-server-control-{mode:o}"));
std::fs::create_dir(&socket_dir).expect("socket dir should be created");
std::fs::set_permissions(&socket_dir, std::fs::Permissions::from_mode(mode))
.expect("socket dir permissions should be changed");
prepare_private_socket_directory(&socket_dir)
.await
.expect("socket dir permissions should be set exactly");
let mode = std::fs::metadata(&socket_dir)
.expect("socket dir metadata")
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o700);
}
}
#[cfg(unix)]
#[tokio::test]
async fn regular_file_path_is_not_stale_socket_path() {
let temp_dir = tempfile::TempDir::new().expect("temp dir");
let regular_file = temp_dir.path().join("not-a-socket");
std::fs::write(&regular_file, b"not a socket").expect("regular file should be created");
assert!(
!is_stale_socket_path(&regular_file)
.await
.expect("stale socket check should succeed")
);
}
#[tokio::test]
async fn bound_listener_path_is_stale_socket_path() {
let temp_dir = tempfile::TempDir::new().expect("temp dir");
let socket_path = temp_dir.path().join("socket");
let _listener = match UnixListener::bind(&socket_path).await {
Ok(listener) => listener,
Err(err) if err.kind() == ErrorKind::PermissionDenied => {
eprintln!("skipping test: failed to bind unix socket: {err}");
return;
}
Err(err) => panic!("failed to bind test socket: {err}"),
};
assert!(
is_stale_socket_path(&socket_path)
.await
.expect("stale socket check should succeed")
);
}
#[tokio::test]
async fn stream_round_trips_data_between_listener_and_client() {
let temp_dir = tempfile::TempDir::new().expect("temp dir");
let socket_path = temp_dir.path().join("socket");
let mut listener = match UnixListener::bind(&socket_path).await {
Ok(listener) => listener,
Err(err) if err.kind() == ErrorKind::PermissionDenied => {
eprintln!("skipping test: failed to bind unix socket: {err}");
return;
}
Err(err) => panic!("failed to bind test socket: {err}"),
};
let server_task = tokio::spawn(async move {
let mut server_stream = listener.accept().await.expect("connection should accept");
let mut request = [0; 7];
server_stream
.read_exact(&mut request)
.await
.expect("server should read request");
assert_eq!(&request, b"request");
server_stream
.write_all(b"response")
.await
.expect("server should write response");
});
let mut client_stream = UnixStream::connect(&socket_path)
.await
.expect("client should connect");
client_stream
.write_all(b"request")
.await
.expect("client should write request");
let mut response = [0; 8];
client_stream
.read_exact(&mut response)
.await
.expect("client should read response");
assert_eq!(&response, b"response");
server_task.await.expect("server task should join");
}
#[cfg(windows)]
#[tokio::test]
async fn implicit_peer_validation_rejects_elevated_listener() {
let temp = tempfile::TempDir::new().unwrap();
let path = temp.path().join("socket");
let mut listener = UnixListener::bind(&path).await.unwrap();
let client = UnixStream::connect(&path).await.unwrap();
let _server = listener.accept().await.unwrap();
// PowerShell inherits our token and supplies an independent elevation oracle.
let output = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", "([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"])
.output().unwrap();
assert!(output.status.success());
let expected = match String::from_utf8(output.stdout).unwrap().trim() {
"True" => Err(ErrorKind::PermissionDenied),
"False" => Ok(()),
other => panic!("unexpected elevation result: {other}"),
};
assert_eq!(
client.ensure_non_elevated_peer().map_err(|err| err.kind()),
expected
);
}

View File

@@ -0,0 +1,103 @@
//! Authenticate implicitly discovered Windows socket peers before sending data.
//! The socket's kernel-reported PID, rather than a PID file, identifies the token.
use std::io;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::os::windows::io::RawSocket;
use std::ptr;
use windows_sys::Win32::Networking::WinSock::SIO_AF_UNIX_GETPEERPID;
use windows_sys::Win32::Networking::WinSock::SOCKET_ERROR;
use windows_sys::Win32::Networking::WinSock::WSAGetLastError;
use windows_sys::Win32::Networking::WinSock::WSAIoctl;
use windows_sys::Win32::Security::EqualSid;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::TOKEN_ELEVATION;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::Security::TOKEN_USER;
use windows_sys::Win32::Security::TokenElevation;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::OpenProcess;
use windows_sys::Win32::System::Threading::OpenProcessToken;
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
pub(super) fn ensure_non_elevated_peer(socket: RawSocket) -> io::Result<()> {
let mut pid = 0u32;
let mut returned = 0;
if unsafe {
WSAIoctl(
socket as _,
SIO_AF_UNIX_GETPEERPID,
ptr::null(),
/*cbinbuffer*/ 0,
ptr::addr_of_mut!(pid).cast(),
std::mem::size_of_val(&pid) as u32,
&mut returned,
ptr::null_mut(),
/*lpcompletionroutine*/ None,
)
} == SOCKET_ERROR
{
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
// Older Windows versions can return a valid PID with zero bytes reported.
if pid == 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"socket peer PID unavailable",
));
}
let process = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
/*binherithandle*/ 0,
pid,
)
};
if process.is_null() {
return Err(io::Error::last_os_error());
}
let _process = unsafe { OwnedHandle::from_raw_handle(process) };
let mut token = ptr::null_mut();
if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 {
return Err(io::Error::last_os_error());
}
let _token = unsafe { OwnedHandle::from_raw_handle(token) };
let mut current_token = ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut current_token) } == 0 {
return Err(io::Error::last_os_error());
}
let _current_token = unsafe { OwnedHandle::from_raw_handle(current_token) };
let current_user = crate::windows_security::token_user(current_token)?;
let peer_user = crate::windows_security::token_user(token)?;
let same_user = unsafe {
EqualSid(
(*(current_user.as_ptr().cast::<TOKEN_USER>())).User.Sid,
(*(peer_user.as_ptr().cast::<TOKEN_USER>())).User.Sid,
) != 0
};
// Implicit reuse must not change either side's elevation context.
for token in [current_token, token] {
let mut elevation: TOKEN_ELEVATION = unsafe { std::mem::zeroed() };
if unsafe {
GetTokenInformation(
token,
TokenElevation,
ptr::addr_of_mut!(elevation).cast(),
std::mem::size_of_val(&elevation) as u32,
&mut returned,
)
} == 0
{
return Err(io::Error::last_os_error());
}
if !same_user || elevation.TokenIsElevated != 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"implicit daemon connection requires non-elevated current-user tokens",
));
}
}
Ok(())
}

View File

@@ -0,0 +1,128 @@
//! Protect Windows socket rendezvous directories with an inheritable user-only
//! DACL at creation time. Reject unsafe existing directories instead of repairing them.
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::ptr;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::Security::TOKEN_USER;
use windows_sys::Win32::Security::TokenUser;
use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::OpenProcessToken;
pub(super) fn prepare_private_directory(path: &Path) -> io::Result<()> {
let user = current_user()?;
let user_sid = unsafe { (*(user.as_ptr().cast::<TOKEN_USER>())).User.Sid };
let mut sid_string = ptr::null_mut();
if unsafe { ConvertSidToStringSidW(user_sid, &mut sid_string) } == 0 {
return Err(io::Error::last_os_error());
}
let mut sid_length = 0;
while unsafe { *sid_string.add(sid_length) } != 0 {
sid_length += 1;
}
let sid =
String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(sid_string, sid_length) });
unsafe { LocalFree(sid_string as _) };
let sddl: Vec<u16> = format!("O:{sid}D:P(A;OICI;FA;;;{sid})")
.encode_utf16()
.chain(Some(0))
.collect();
let mut descriptor = ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
/*stringsdrevision*/ 1,
&mut descriptor,
ptr::null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
let result = (|| {
// Canonicalize only the parent: this supplies Win32's extended-length
// prefix without following a reparse point at the directory being secured.
let absolute = std::path::absolute(path)?;
let path = match (absolute.parent(), absolute.file_name()) {
(Some(parent), Some(name)) => {
std::fs::create_dir_all(parent)?;
std::fs::canonicalize(parent)?.join(name)
}
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"private directory must not be a filesystem root",
));
}
};
let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor,
bInheritHandle: 0,
};
if unsafe { CreateDirectoryW(path_wide.as_ptr(), &attributes) } != 0 {
return Ok(());
}
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(err);
}
// Changing a DACL cannot revoke handles already held by another user.
// Existing directories must already meet our private-directory contract.
let _guard = crate::windows_socket_validation::validate_private_directory(&path)?;
Ok(())
})();
unsafe { LocalFree(descriptor as _) };
result
}
// Keep the pointer-aligned buffer alive while using its TOKEN_USER SID.
pub(super) fn current_user() -> io::Result<Vec<usize>> {
// Token information contains pointers, so allocate pointer-aligned storage.
let mut token = ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return Err(io::Error::last_os_error());
}
let _token = unsafe { OwnedHandle::from_raw_handle(token) };
token_user(token)
}
pub(super) fn token_user(token: HANDLE) -> io::Result<Vec<usize>> {
let mut length = 0;
unsafe {
GetTokenInformation(
token,
TokenUser,
ptr::null_mut(),
/*tokeninformationlength*/ 0,
&mut length,
)
};
let mut user = vec![0usize; (length as usize).div_ceil(std::mem::size_of::<usize>())];
if unsafe {
GetTokenInformation(
token,
TokenUser,
user.as_mut_ptr().cast(),
length,
&mut length,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(user)
}

View File

@@ -0,0 +1,138 @@
//! Read-only validation of Windows daemon rendezvous directories. Pin the
//! validated directory while connecting; never repair an untrusted listener's ACL.
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::ACCESS_ALLOWED_ACE;
use windows_sys::Win32::Security::ACE_HEADER;
use windows_sys::Win32::Security::Authorization::GetSecurityInfo;
use windows_sys::Win32::Security::Authorization::SE_FILE_OBJECT;
use windows_sys::Win32::Security::CONTAINER_INHERIT_ACE;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::EqualSid;
use windows_sys::Win32::Security::GetAce;
use windows_sys::Win32::Security::GetSecurityDescriptorControl;
use windows_sys::Win32::Security::OBJECT_INHERIT_ACE;
use windows_sys::Win32::Security::OWNER_SECURITY_INFORMATION;
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
use windows_sys::Win32::Security::TOKEN_USER;
use windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_LIST_DIRECTORY;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
/// Validates an existing daemon socket directory without creating or changing it.
/// Connect using the returned path and retain the handle through connection setup
/// to prevent replacement of the validated directory. Ancestor junctions are
/// resolved before validation; the socket directory itself must not be a reparse point.
pub fn validate_private_socket_path(socket_path: &Path) -> io::Result<(PathBuf, OwnedHandle)> {
let absolute = std::path::absolute(socket_path)?;
let directory = absolute.parent().ok_or(io::ErrorKind::InvalidInput)?;
let socket_name = absolute.file_name().ok_or(io::ErrorKind::InvalidInput)?;
let (directory, guard) = validate_private_directory(directory)?;
Ok((directory.join(socket_name), guard))
}
pub(super) fn validate_private_directory(directory: &Path) -> io::Result<(PathBuf, OwnedHandle)> {
let parent = directory.parent().ok_or(io::ErrorKind::InvalidInput)?;
let directory_name = directory.file_name().ok_or(io::ErrorKind::InvalidInput)?;
let directory = std::fs::canonicalize(parent)?.join(directory_name);
let path_wide: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect();
// Metadata-only access does not enforce sharing restrictions on Windows.
// Directory listing access makes omission of FILE_SHARE_DELETE pin the path.
let handle = unsafe {
CreateFileW(
path_wide.as_ptr(),
READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let guard = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
if info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0
|| info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"untrusted socket directory",
));
}
let user = crate::windows_security::current_user()?;
let user_sid = unsafe { (*(user.as_ptr().cast::<TOKEN_USER>())).User.Sid };
let mut owner = ptr::null_mut();
let mut dacl = ptr::null_mut();
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetSecurityInfo(
handle,
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&mut owner,
ptr::null_mut(),
&mut dacl,
ptr::null_mut(),
&mut descriptor,
)
};
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32));
}
// Accept exactly the protected, inheritable user-only ACL set at daemon bind.
let trusted = unsafe {
let mut control = 0;
let mut revision = 0;
let mut ace = ptr::null_mut();
!owner.is_null()
&& EqualSid(owner, user_sid) != 0
&& GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) != 0
&& control & SE_DACL_PROTECTED != 0
&& !dacl.is_null()
&& (*dacl).AceCount == 1
&& GetAce(dacl, /*dwaceindex*/ 0, &mut ace) != 0
&& (*ace.cast::<ACE_HEADER>()).AceType == ACCESS_ALLOWED_ACE_TYPE as u8
&& (*ace.cast::<ACE_HEADER>()).AceFlags
== (CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE) as u8
&& (*ace.cast::<ACCESS_ALLOWED_ACE>()).Mask == FILE_ALL_ACCESS
&& EqualSid(
ptr::addr_of_mut!((*ace.cast::<ACCESS_ALLOWED_ACE>()).SidStart).cast(),
user_sid,
) != 0
};
unsafe { LocalFree(descriptor as _) };
if !trusted {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"socket directory is not private to the current user",
));
}
Ok((directory, guard))
}