Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

6.9 KB
Raw Blame
use std::fs::File;
use std::io::{self, Write};
use std::mem::{replace, size_of};
use std::os::windows::io::{AsRawHandle, FromRawHandle};
use std::path::Path;
use std::ptr::from_mut;

use anyhow::{Context, Result};
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use windows::core::{Owned, HSTRING, PWSTR};
use windows::Win32::Foundation::{GENERIC_WRITE, HANDLE, HLOCAL};
use windows::Win32::Security::Authorization::{
    ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows::Win32::Security::{
    GetTokenInformation, TokenUser, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY,
};
use windows::Win32::Storage::FileSystem::{
    CreateFileW, GetVolumeInformationByHandleW, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_NONE,
};
use windows::Win32::System::SystemServices::{FILE_PERSISTENT_ACLS, SE_TOKEN_USER};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

use super::{pipe_name, random_token, EDITION};

fn current_user_sid() -> windows::core::Result<String> {
    // SE_TOKEN_USER is sized and aligned for TOKEN_USER and its largest possible SID.
    // The SID points into this buffer until ConvertSidToStringSidW copies it.
    unsafe {
        let mut token = Owned::<HANDLE>::default();
        OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut *token)?;
        let mut user = SE_TOKEN_USER::default();
        let mut bytes = 0;
        GetTokenInformation(
            *token,
            TokenUser,
            Some(from_mut(&mut user).cast()),
            size_of::<SE_TOKEN_USER>() as u32,
            &mut bytes,
        )?;
        sid_string(user.Anonymous1.User.Sid)
    }
}

// The caller keeps the buffer containing the SID alive for the conversion.
unsafe fn sid_string(sid: PSID) -> windows::core::Result<String> {
    let mut text = PWSTR::null();
    ConvertSidToStringSidW(sid, &mut text)?;
    let _allocation = Owned::new(HLOCAL(text.0.cast()));
    Ok(text.to_string()?)
}

/// A self-relative security descriptor allocated by Windows and freed with LocalFree.
struct UserSecurity(Owned<HLOCAL>);

// SAFETY: the descriptor owns its storage, is immutable after construction, and
// LocalFree has no thread affinity. The listener may move between runtime threads.
unsafe impl Send for UserSecurity {}

impl UserSecurity {
    fn new() -> Result<Self> {
        let sid = current_user_sid().context("read process user SID")?;
        // Set the owner explicitly too: an elevated token can default to Administrators.
        let sddl = HSTRING::from(format!("O:{sid}D:P(A;;GA;;;{sid})"));
        let mut descriptor = PSECURITY_DESCRIPTOR::default();
        unsafe {
            ConvertStringSecurityDescriptorToSecurityDescriptorW(
                &sddl,
                SDDL_REVISION_1,
                &mut descriptor,
                None,
            )
            .context("build agent bridge security descriptor")?;
            Ok(Self(Owned::new(HLOCAL(descriptor.0))))
        }
    }

    fn attributes(&self) -> SECURITY_ATTRIBUTES {
        SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: (*self.0).0,
            bInheritHandle: false.into(),
        }
    }

    fn create_pipe(&self, name: &str, first: bool) -> io::Result<NamedPipeServer> {
        let mut attrs = self.attributes();
        // CreateNamedPipeW consumes the attributes during this call.
        unsafe {
            ServerOptions::new()
                .first_pipe_instance(first)
                .reject_remote_clients(true)
                .create_with_security_attributes_raw(name, from_mut(&mut attrs).cast())
        }
    }
}

pub(super) struct PipeListener {
    pub(super) name: String,
    security: UserSecurity,
    pending: NamedPipeServer,
}

impl PipeListener {
    pub(super) fn bind() -> Result<Self> {
        // Independent of the bearer token: pipe names can be enumerated locally.
        let name = pipe_name(EDITION, &random_token());
        let security = UserSecurity::new()?;
        let pending = security
            .create_pipe(&name, true)
            .context("bind agent bridge pipe")?;
        Ok(Self {
            name,
            security,
            pending,
        })
    }

    pub(super) async fn accept(&mut self) -> Result<NamedPipeServer> {
        loop {
            let connected = self.pending.connect().await;
            // Keep the name continuously bound, including when a client disconnects
            // before connect completes. Hand off only after the successor is ready.
            let next = self
                .security
                .create_pipe(&self.name, false)
                .context("create the next agent bridge pipe instance")?;
            let client = replace(&mut self.pending, next);
            match connected {
                Ok(()) => return Ok(client),
                Err(err) => tracing::warn!("agent bridge pipe connect error: {err}"),
            }
        }
    }
}

pub(super) fn write_discovery_file(path: &Path, contents: &str) -> Result<()> {
    let security = UserSecurity::new()?;
    // canonicalize supplies the extended-length path for CreateFileW even for a
    // deeply nested profile. The rename stays on the same volume.
    let parent = path.parent().context("resolve discovery directory")?;
    let tmp = parent
        .canonicalize()?
        .join(format!("{}.tmp", uuid::Uuid::new_v4()));
    // CREATE_NEW ensures these attributes apply to a new file, even after a
    // crash. No handle is shared while we write the bearer token.
    let mut file = unsafe {
        let handle = CreateFileW(
            &HSTRING::from(tmp.as_os_str()),
            GENERIC_WRITE.0,
            FILE_SHARE_NONE,
            Some(&security.attributes()),
            CREATE_NEW,
            FILE_ATTRIBUTE_NORMAL,
            None,
        )
        .context("create private discovery temp file")?;
        File::from_raw_handle(handle.0)
    };
    let result = (|| {
        // FAT, for example, silently ignores security descriptors. Check the
        // actual open file's volume before putting a secret in it.
        let mut flags = 0;
        unsafe {
            GetVolumeInformationByHandleW(
                HANDLE(file.as_raw_handle()),
                None,
                None,
                None,
                Some(&mut flags),
                None,
            )
        }
        .context("check discovery volume permissions")?;
        anyhow::ensure!(
            flags & FILE_PERSISTENT_ACLS != 0,
            "discovery volume does not enforce ACLs"
        );
        file.write_all(contents.as_bytes())
            .context("write discovery temp file")?;
        file.sync_all().context("flush discovery temp file")?;
        drop(file);
        std::fs::rename(&tmp, path).context("rename discovery file into place")
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(tmp);
    }
    result
}

#[cfg(test)]
mod tests;