296 lines
10 KiB
Rust
296 lines
10 KiB
Rust
use crate::{read_frame, write_frame, Request, Response};
|
|
use anyhow::{bail, Context, Result};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
future::Future,
|
|
path::{Path, PathBuf},
|
|
pin::Pin,
|
|
sync::Arc,
|
|
time::Duration,
|
|
};
|
|
use tokio::{
|
|
io::{AsyncRead, AsyncWrite},
|
|
task::JoinSet,
|
|
time::timeout,
|
|
};
|
|
pub type Handler =
|
|
Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send>> + Send + Sync>;
|
|
fn absolute(path: &Path) -> Result<PathBuf> {
|
|
Ok(
|
|
std::fs::canonicalize(path.parent().context("missing config parent")?)?
|
|
.join(path.file_name().context("missing config filename")?),
|
|
)
|
|
}
|
|
pub fn endpoint(config: &Path) -> Result<String> {
|
|
let path = absolute(config)?;
|
|
if cfg!(windows) {
|
|
let normalized = path.to_string_lossy().to_lowercase();
|
|
let hash = Sha256::digest(normalized.as_bytes());
|
|
Ok(format!(r"\\.\pipe\ttstd-ads-{:x}", hash))
|
|
} else {
|
|
let hash = format!(
|
|
"{:x}",
|
|
Sha256::digest(path.file_name().unwrap().as_encoded_bytes())
|
|
);
|
|
Ok(path
|
|
.parent()
|
|
.unwrap()
|
|
.join(format!("agent-{}.sock", &hash[..16]))
|
|
.to_string_lossy()
|
|
.into_owned())
|
|
}
|
|
}
|
|
async fn connection(
|
|
mut socket: impl AsyncRead + AsyncWrite + Unpin,
|
|
handler: Handler,
|
|
) -> Result<()> {
|
|
let request = timeout(Duration::from_secs(5), read_frame(&mut socket)).await??;
|
|
let response = timeout(Duration::from_secs(12), handler(request)).await?;
|
|
timeout(Duration::from_secs(5), write_frame(&mut socket, &response)).await??;
|
|
Ok(())
|
|
}
|
|
pub async fn request(config: &Path, value: &Request) -> Result<Response> {
|
|
let name = endpoint(config)?;
|
|
timeout(Duration::from_secs(15), async {
|
|
#[cfg(windows)]
|
|
let connect_deadline = std::time::Instant::now() + Duration::from_secs(3);
|
|
#[cfg(windows)]
|
|
let mut socket = loop {
|
|
match tokio::net::windows::named_pipe::ClientOptions::new().open(&name) {
|
|
Ok(socket) => break socket,
|
|
Err(error)
|
|
if matches!(error.raw_os_error(), Some(2 | 231))
|
|
&& std::time::Instant::now() < connect_deadline =>
|
|
{
|
|
tokio::time::sleep(Duration::from_millis(50)).await
|
|
}
|
|
Err(error) => return Err(error.into()),
|
|
}
|
|
};
|
|
#[cfg(unix)]
|
|
let mut socket = tokio::net::UnixStream::connect(&name)
|
|
.await
|
|
.context("agent is not running or local socket is inaccessible")?;
|
|
write_frame(&mut socket, value).await?;
|
|
read_frame(&mut socket).await
|
|
})
|
|
.await
|
|
.context("local agent management timed out")?
|
|
}
|
|
#[cfg(unix)]
|
|
pub async fn serve(
|
|
config: &Path,
|
|
handler: Handler,
|
|
ready: tokio::sync::oneshot::Sender<()>,
|
|
) -> Result<()> {
|
|
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
|
|
let name = endpoint(config)?;
|
|
let path = PathBuf::from(&name);
|
|
let directory = std::fs::metadata(path.parent().unwrap())?;
|
|
if directory.mode() & 0o022 != 0 {
|
|
bail!("config directory must not be writable by other users")
|
|
}
|
|
let owner = directory.uid();
|
|
if path.exists() {
|
|
if tokio::net::UnixStream::connect(&path).await.is_ok() {
|
|
bail!("agent already running")
|
|
}
|
|
let metadata = std::fs::symlink_metadata(&path)?;
|
|
if !metadata.file_type().is_socket() || metadata.uid() != owner {
|
|
bail!("refusing to remove a foreign socket path")
|
|
}
|
|
std::fs::remove_file(&path)?;
|
|
}
|
|
let listener = tokio::net::UnixListener::bind(&path)?;
|
|
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
|
let cpath = std::ffi::CString::new(name)?;
|
|
if unsafe { libc::geteuid() } == 0
|
|
&& unsafe { libc::chown(cpath.as_ptr(), owner, u32::MAX) } != 0
|
|
{
|
|
bail!("cannot set local socket owner")
|
|
}
|
|
struct Cleanup(PathBuf);
|
|
impl Drop for Cleanup {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_file(&self.0);
|
|
}
|
|
}
|
|
let _cleanup = Cleanup(path);
|
|
let _ = ready.send(());
|
|
let mut tasks = JoinSet::new();
|
|
loop {
|
|
tokio::select! {
|
|
accepted=listener.accept()=>{let(socket,_)=accepted?;if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
|
|
_=tasks.join_next(),if !tasks.is_empty()=>{},
|
|
}
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
pub async fn serve(
|
|
config: &Path,
|
|
handler: Handler,
|
|
ready: tokio::sync::oneshot::Sender<()>,
|
|
) -> Result<()> {
|
|
use tokio::net::windows::named_pipe::ServerOptions;
|
|
let name = endpoint(config)?;
|
|
let security = Security::new(config.parent().context("missing config directory")?)?;
|
|
let create = |first: bool| -> Result<_> {
|
|
let mut attributes = security.attributes();
|
|
Ok(unsafe {
|
|
ServerOptions::new()
|
|
.first_pipe_instance(first)
|
|
.reject_remote_clients(true)
|
|
.create_with_security_attributes_raw(&name, &mut attributes as *mut _ as *mut _)
|
|
}?)
|
|
};
|
|
let mut server = create(true)
|
|
.context("cannot create private management pipe; agent may already be running")?;
|
|
let _ = ready.send(());
|
|
let mut tasks = JoinSet::new();
|
|
loop {
|
|
tokio::select! {
|
|
connected=server.connect()=>{connected?;let next=create(false)?;let socket=std::mem::replace(&mut server,next);if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
|
|
_=tasks.join_next(),if !tasks.is_empty()=>{},
|
|
}
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
pub fn owner_sid(path: &Path) -> Result<String> {
|
|
use std::os::windows::ffi::OsStrExt;
|
|
use windows_sys::Win32::{
|
|
Foundation::LocalFree,
|
|
Security::{
|
|
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
|
OWNER_SECURITY_INFORMATION,
|
|
},
|
|
};
|
|
let name: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
let mut owner = std::ptr::null_mut();
|
|
let mut descriptor = std::ptr::null_mut();
|
|
let code = unsafe {
|
|
GetNamedSecurityInfoW(
|
|
name.as_ptr(),
|
|
SE_FILE_OBJECT,
|
|
OWNER_SECURITY_INFORMATION,
|
|
&mut owner,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut descriptor,
|
|
)
|
|
};
|
|
if code != 0 {
|
|
bail!("cannot read config directory owner: {code}")
|
|
}
|
|
let mut sid = std::ptr::null_mut();
|
|
let result = unsafe { ConvertSidToStringSidW(owner, &mut sid) };
|
|
if result == 0 {
|
|
unsafe { LocalFree(descriptor) };
|
|
bail!("cannot format config owner SID")
|
|
}
|
|
let mut length = 0;
|
|
unsafe {
|
|
while *sid.add(length) != 0 {
|
|
length += 1;
|
|
}
|
|
}
|
|
let result = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(sid, length) });
|
|
unsafe {
|
|
LocalFree(sid as _);
|
|
LocalFree(descriptor);
|
|
}
|
|
Ok(result)
|
|
}
|
|
#[cfg(windows)]
|
|
struct Security(*mut std::ffi::c_void);
|
|
#[cfg(windows)]
|
|
unsafe impl Send for Security {}
|
|
#[cfg(windows)]
|
|
impl Security {
|
|
fn new(directory: &Path) -> Result<Self> {
|
|
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
|
|
let owner = owner_sid(directory)?;
|
|
let sddl: Vec<u16> = format!("D:P(A;;GA;;;SY)(A;;GA;;;{owner})")
|
|
.encode_utf16()
|
|
.chain(Some(0))
|
|
.collect();
|
|
let mut descriptor = std::ptr::null_mut();
|
|
if unsafe {
|
|
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
sddl.as_ptr(),
|
|
1,
|
|
&mut descriptor,
|
|
std::ptr::null_mut(),
|
|
)
|
|
} == 0
|
|
{
|
|
bail!("cannot create private pipe ACL")
|
|
};
|
|
Ok(Self(descriptor))
|
|
}
|
|
fn attributes(&self) -> windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
|
|
windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
|
|
nLength: std::mem::size_of::<windows_sys::Win32::Security::SECURITY_ATTRIBUTES>()
|
|
as u32,
|
|
lpSecurityDescriptor: self.0,
|
|
bInheritHandle: 0,
|
|
}
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
impl Drop for Security {
|
|
fn drop(&mut self) {
|
|
unsafe { windows_sys::Win32::Foundation::LocalFree(self.0) };
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
|
|
let sid = owner_sid(parent)?;
|
|
use std::os::windows::process::CommandExt;
|
|
let status = std::process::Command::new("icacls.exe")
|
|
.creation_flags(0x08000000)
|
|
.arg(path)
|
|
.args([
|
|
"/inheritance:r",
|
|
"/grant:r",
|
|
&format!("*{sid}:(F)"),
|
|
"*S-1-5-18:(F)",
|
|
"/Q",
|
|
])
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::null())
|
|
.status()?;
|
|
if !status.success() {
|
|
bail!("cannot restrict private file permissions")
|
|
};
|
|
Ok(())
|
|
}
|
|
#[cfg(unix)]
|
|
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
|
|
use std::os::unix::ffi::OsStrExt;
|
|
use std::os::unix::fs::MetadataExt;
|
|
let metadata = std::fs::metadata(parent)?;
|
|
if metadata.mode() & 0o022 != 0 {
|
|
bail!("config directory must not be writable by other users")
|
|
}
|
|
if unsafe { libc::geteuid() } == 0 {
|
|
let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
|
|
if unsafe { libc::chown(path.as_ptr(), metadata.uid(), u32::MAX) } != 0 {
|
|
bail!("cannot preserve config owner")
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#[test]
|
|
fn config_filenames_have_isolated_management_endpoints() {
|
|
let folder = std::env::temp_dir();
|
|
assert_ne!(
|
|
super::endpoint(&folder.join("first-agent.json")).unwrap(),
|
|
super::endpoint(&folder.join("second-agent.json")).unwrap()
|
|
);
|
|
}
|
|
}
|