#![allow(unsafe_code)]
use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::Path;
use std::ptr;
use std::sync::OnceLock;
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use windows_sys::Win32::Foundation::{GENERIC_WRITE, INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
SE_FILE_OBJECT, SetNamedSecurityInfoW,
};
use windows_sys::Win32::Security::{
ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, GetTokenInformation, OWNER_SECURITY_INFORMATION,
PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_ACCESS_MASK,
TOKEN_QUERY, TOKEN_USER, TokenUser,
};
use windows_sys::Win32::Storage::FileSystem::{
CREATE_NEW, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, READ_CONTROL,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
const ALSO_TRUSTED: [&str; 2] = ["S-1-5-32-544", "S-1-5-18"];
pub(crate) fn protect_dir(path: &Path) -> io::Result<()> {
let refused = |why: &str| io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: {why}", path.display()));
let held = held_in_place(path).map_err(|error| within(path, "opening it", &error))?;
let attributes = held.metadata().map_err(|error| within(path, "reading its attributes", &error))?;
if attributes.file_type().is_symlink() {
return Err(refused("a link, where the server keeps a directory of its own"));
}
let owner = owner_of(&held).map_err(|error| within(path, "reading its owner", &error))?;
if !may_own(&owner)? {
return Err(refused(&format!(
"owned by {owner} rather than the user the server runs as, so its owner could let anyone in \
whatever its DACL says; remove it, and serve makes it again"
)));
}
let descriptor = Descriptor::parse(&format!("D:P(A;OICI;FA;;;{})", user()?))?;
descriptor.set_on(path).map_err(|error| within(path, "making it the user's alone", &error))?;
drop(held);
Ok(())
}
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
let descriptor = Descriptor::parse(&format!("D:P(A;;FA;;;{})", user()?))?;
descriptor.create_file(path).map_err(|error| within(path, "creating it the user's alone", &error))
}
pub(crate) fn create_pipe(options: &ServerOptions, name: &str) -> io::Result<NamedPipeServer> {
Descriptor::parse(&format!("D:P(A;;FA;;;{})", user()?))?.create_pipe(options, name)
}
fn user() -> io::Result<&'static str> {
static USER: OnceLock<String> = OnceLock::new();
if let Some(user) = USER.get() {
return Ok(user);
}
let user = spelled(token_user(&process_token(TOKEN_QUERY)?)?.sid())?;
Ok(USER.get_or_init(|| user))
}
fn may_own(owner: &str) -> io::Result<bool> {
Ok(owner == user()? || ALSO_TRUSTED.contains(&owner))
}
fn held_in_place(path: &Path) -> io::Result<File> {
OpenOptions::new()
.access_mode(READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_LIST_DIRECTORY)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
}
fn owner_of(file: &File) -> io::Result<String> {
let (mut owner, mut descriptor) = (ptr::null_mut(), ptr::null_mut());
let failed = unsafe {
GetSecurityInfo(
file.as_raw_handle(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
&raw mut owner,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&raw mut descriptor,
)
};
if failed != 0 {
return Err(io::Error::from_raw_os_error(failed.cast_signed()));
}
let spelled = spelled(owner);
unsafe { LocalFree(descriptor) };
spelled
}
fn within(path: &Path, doing: &str, error: &io::Error) -> io::Error {
io::Error::new(error.kind(), format!("{}: {doing}: {error}", path.display()))
}
struct Descriptor(PSECURITY_DESCRIPTOR);
impl Descriptor {
fn parse(sddl: &str) -> io::Result<Descriptor> {
let sddl = wide(OsStr::new(sddl));
let mut descriptor = ptr::null_mut();
let done = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&raw mut descriptor,
ptr::null_mut(),
)
};
if done == 0 {
return Err(io::Error::last_os_error());
}
Ok(Descriptor(descriptor))
}
fn set_on(&self, path: &Path) -> io::Result<()> {
let (mut present, mut dacl, mut defaulted) = (0, ptr::null_mut::<ACL>(), 0);
let done = unsafe { GetSecurityDescriptorDacl(self.0, &raw mut present, &raw mut dacl, &raw mut defaulted) };
if done == 0 {
return Err(io::Error::last_os_error());
}
let path = wide(path.as_os_str());
let information = DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION;
let failed = unsafe {
SetNamedSecurityInfoW(
path.as_ptr(),
SE_FILE_OBJECT,
information,
ptr::null_mut(),
ptr::null_mut(),
dacl,
ptr::null(),
)
};
match failed {
0 => Ok(()),
failed => Err(io::Error::from_raw_os_error(failed.cast_signed())),
}
}
fn create_pipe(&self, options: &ServerOptions, name: &str) -> io::Result<NamedPipeServer> {
let mut attributes = self.attributes();
unsafe { options.create_with_security_attributes_raw(name, (&raw mut attributes).cast()) }
}
fn create_file(&self, path: &Path) -> io::Result<File> {
let attributes = self.attributes();
let path = wide(path.as_os_str());
let shared = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
let handle = unsafe {
CreateFileW(
path.as_ptr(),
GENERIC_WRITE,
shared,
&raw const attributes,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(File::from(unsafe { OwnedHandle::from_raw_handle(handle) }))
}
fn attributes(&self) -> SECURITY_ATTRIBUTES {
SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: self.0,
bInheritHandle: 0,
}
}
}
impl Drop for Descriptor {
fn drop(&mut self) {
unsafe { LocalFree(self.0) };
}
}
fn process_token(access: TOKEN_ACCESS_MASK) -> io::Result<OwnedHandle> {
let mut token = ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &raw mut token) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { OwnedHandle::from_raw_handle(token) })
}
struct UserOf(Vec<u64>);
impl UserOf {
fn sid(&self) -> PSID {
unsafe { (*self.0.as_ptr().cast::<TOKEN_USER>()).User.Sid }
}
}
fn token_user(token: &OwnedHandle) -> io::Result<UserOf> {
let mut size = 0;
unsafe { GetTokenInformation(token.as_raw_handle(), TokenUser, ptr::null_mut(), 0, &raw mut size) };
let mut buffer = vec![0_u64; (size as usize).div_ceil(8)];
let done = unsafe {
GetTokenInformation(token.as_raw_handle(), TokenUser, buffer.as_mut_ptr().cast(), size, &raw mut size)
};
if done == 0 {
return Err(io::Error::last_os_error());
}
Ok(UserOf(buffer))
}
fn spelled(sid: PSID) -> io::Result<String> {
let mut text = ptr::null_mut();
if unsafe { ConvertSidToStringSidW(sid, &raw mut text) } == 0 {
return Err(io::Error::last_os_error());
}
let spelled = unsafe {
let length = (0..).take_while(|&at| *text.add(at) != 0).count();
let spelled = OsString::from_wide(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
spelled
};
spelled.into_string().map_err(|_| io::Error::other("a SID spelled other than in ASCII"))
}
fn wide(text: &OsStr) -> Vec<u16> {
text.encode_wide().chain(Some(0)).collect()
}
#[cfg(test)]
#[path = "owner_only_tests.rs"]
mod tests;