Add viewer RPC backend for ironrdp-agent

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Marc-André Moreau
2026-08-02 23:35:31 -04:00
parent f614e4acfc
commit 50138b98ec
24 changed files with 2938 additions and 2354 deletions
Generated
+18 -2
View File
@@ -2451,11 +2451,11 @@ dependencies = [
"clap",
"ironrdp-cfg",
"ironrdp-client",
"ironrdp-core 0.2.1",
"ironrdp-input",
"ironrdp-pdu",
"ironrdp-propertyset",
"ironrdp-rdpfile",
"ironrdp-rpc",
"ironrdp-tls",
"libc",
"now-client",
@@ -2467,7 +2467,6 @@ dependencies = [
"tracing-subscriber",
"uuid",
"whoami",
"windows",
]
[[package]]
@@ -2896,6 +2895,22 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "ironrdp-rpc"
version = "0.1.0"
dependencies = [
"anyhow",
"ironrdp-core 0.2.1",
"ironrdp-input",
"ironrdp-pdu",
"ironrdp-propertyset",
"libc",
"tokio",
"tracing",
"whoami",
"windows",
]
[[package]]
name = "ironrdp-server"
version = "0.13.0"
@@ -3070,6 +3085,7 @@ dependencies = [
"clap",
"inquire",
"ironrdp",
"ironrdp-agent",
"ironrdp-cfg",
"ironrdp-propertyset",
"ironrdp-rdpfile",
+12 -3
View File
@@ -99,7 +99,8 @@ rendering.
ironrdp-viewer <HOSTNAME> --username <USERNAME> --password <PASSWORD>
```
Omitted credentials are prompted for interactively. You can also load a `.rdp` file:
Omitted connection values are prompted for interactively. You can also provide them through
`RDP_HOSTNAME`, `RDP_USERNAME`, and `RDP_PASSWORD`, or load a `.rdp` file:
```shell
ironrdp-viewer --rdp-file ./my-server.rdp
@@ -111,15 +112,23 @@ logging, and the full option list.
### `ironrdp-agent`
`ironrdp-agent` combines a long-lived RDP daemon with short-lived CLI invocations, which makes it
convenient for scripts and LLM-driven automation:
`ironrdp-agent` combines a long-lived local RPC backend with short-lived CLI invocations, which makes
it convenient for scripts and LLM-driven automation. The daemon backend remains the default; use
`--backend viewer` to drive a visible `ironrdp-viewer` window instead:
```shell
ironrdp-agent daemon-start --overlay ./credentials.rdp # in one terminal
ironrdp-agent connect --server <HOSTNAME> --username <USER> # in another
ironrdp-agent screenshot ./desktop.png
ironrdp-agent --backend viewer connect --server <HOSTNAME> --username <USER> --password <PASS>
```
Normal operations automatically start and reuse the selected backend. The daemon and viewer use
distinct per-user endpoints by default; `--endpoint` overrides either one. Run
`ironrdp-agent --backend viewer stop` (or `stop` with the default backend) to terminate the selected
long-lived process. The viewer backend implements the same status, input, screenshot, and NOW
operations while rendering the shared session in its GUI.
`connect` fails with `missing required fields` unless credentials are available, so either preload
them into the daemon with `daemon-start --overlay <FILE>` — which keeps secrets away from the IPC
caller — or pass `--password` to `connect`.
+1 -9
View File
@@ -29,13 +29,13 @@ internal = []
ironrdp-client = { path = "../ironrdp-client", version = "0.1", features = ["rustls", "dvc-pipe-proxy"] }
# Configuration model and codecs
ironrdp-core = { path = "../ironrdp-core", version = "0.2", features = ["alloc"] }
ironrdp-pdu = { path = "../ironrdp-pdu", version = "0.9" }
ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" }
ironrdp-cfg = { path = "../ironrdp-cfg", version = "0.1" }
ironrdp-rdpfile = { path = "../ironrdp-rdpfile", version = "0.1" }
ironrdp-input = { path = "../ironrdp-input", version = "0.7" }
ironrdp-tls = { path = "../ironrdp-tls", version = "0.2" }
ironrdp-rpc = { path = "../ironrdp-rpc", version = "0.1" }
# Async runtime and IPC transport
tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "macros", "io-util", "time", "signal"] }
@@ -66,13 +66,5 @@ now-proto-pdu = { version = "0.4", features = ["std"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Threading",
] }
[lints]
workspace = true
+20 -4
View File
@@ -1,15 +1,24 @@
# IronRDP Agent
A CLI-driven, daemon-backed RDP client designed for programmatic (e.g. LLM) consumption.
A CLI-driven RDP client designed for programmatic (e.g. LLM) consumption.
The single `ironrdp-agent` binary bundles two roles:
The single `ironrdp-agent` binary provides a short-lived CLI and can drive either of two
long-lived local RPC backends:
- **Daemon** (`ironrdp-agent daemon-start`): a long-lived, foreground process that owns the
[`ironrdp-client`] engine and one RDP session. It stays alive across many CLI invocations and
serves requests over a local IPC transport (a Unix domain socket on Unix, a named pipe on
Windows).
- **CLI** (`ironrdp-agent <op> …`): a short-lived invocation that opens the IPC endpoint, sends a
single request, prints the response, and exits.
- **Viewer** (`ironrdp-viewer --rpc`): the same RPC contract hosted by the visible
[`ironrdp-viewer`]. The viewer window and CLI share one RDP session, framebuffer, and input path.
For normal CLI operations, the selected backend is started automatically when it is not already
running and remains available for later invocations. The daemon is the default; select the visible
viewer with `--backend viewer`. `--endpoint` overrides the selected backend's endpoint. Use
`stop` to terminate the selected backend.
The CLI (`ironrdp-agent <op> …`) is a short-lived invocation that opens the selected endpoint, sends
a single request, prints the response, and exits.
Run `ironrdp-agent --help-agent` for a structured, machine-readable description of every operation.
@@ -31,6 +40,13 @@ strictly-typed messages. `Request::Screenshot` returns the most recent frame as
mouse cursor composited in — the agent enables software pointer rendering), which the CLI writes to
disk.
Both backends implement the complete current RPC contract, including connection lifecycle, status,
property and log inspection, screenshots, mouse/keyboard/resize input, and NOW operations. The
default endpoints are `ironrdp-agent-<uid>.sock` (Unix) or `\\.\pipe\ironrdp-agent-<user>` (Windows)
for the daemon, and the corresponding `ironrdp-viewer-<uid>.sock` or
`\\.\pipe\ironrdp-viewer-<user>` endpoint for the viewer. A manually started viewer uses
`ironrdp-viewer --rpc --rpc-endpoint <PATH-OR-PIPE>` when a non-default endpoint is required.
## Secrets
The daemon never exposes secrets to the IPC reader. `ConfigBuilder::build` strips every
+101 -11
View File
@@ -15,9 +15,12 @@ use core::fmt;
use core::str::FromStr;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command as ProcessCommand, Stdio};
use std::time::Instant;
use anyhow::Context as _;
use clap::{Args, CommandFactory as _, Parser, Subcommand, ValueEnum};
use core::time::Duration as StdDuration;
use ironrdp_cfg::{PropertySetExt as _, TargetAddr};
use ironrdp_input::MouseButton;
use ironrdp_propertyset::{PropertySet, Value};
@@ -40,6 +43,10 @@ pub struct Cli {
#[arg(long, global = true)]
endpoint: Option<String>,
/// Select the local RPC backend. The daemon remains the default.
#[arg(long, global = true, value_enum, default_value_t = Backend::Daemon)]
backend: Backend,
#[command(subcommand)]
command: Option<Command>,
}
@@ -52,6 +59,8 @@ enum Command {
Connect(ConnectArgs),
/// Tear down the current RDP session (the daemon keeps running).
Disconnect,
/// Stop the selected long-lived RPC backend.
Stop,
/// Report the current session status.
Status,
/// Query the live session properties.
@@ -246,6 +255,12 @@ enum OutputFormat {
const MAX_JSON_STREAM_EVENTS: usize = 8 * 1024;
const MAX_JSON_STREAM_OUTPUT: usize = 2 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum Backend {
Daemon,
Viewer,
}
/// A daemon-provided error that must be rendered according to the selected NOW output format.
#[derive(Debug)]
struct NowRequestError(AgentError);
@@ -414,7 +429,7 @@ pub async fn run(cli: Cli) -> anyhow::Result<()> {
return Ok(());
}
let endpoint = endpoint_from_arg(cli.endpoint);
let endpoint = endpoint_from_arg(cli.endpoint, cli.backend);
let Some(command) = cli.command else {
let _ = Cli::command().print_help();
@@ -422,11 +437,19 @@ pub async fn run(cli: Cli) -> anyhow::Result<()> {
return Ok(());
};
if !matches!(&command, Command::DaemonStart(_) | Command::Stop) {
ensure_backend(&endpoint, cli.backend).await?;
}
let request = match command {
Command::DaemonStart(args) => {
if cli.backend != Backend::Daemon {
anyhow::bail!("daemon-start requires --backend daemon");
}
let overlay = load_overlay(args.overlay.as_deref(), args.prop)?;
return crate::daemon::run(endpoint, overlay).await;
}
Command::Stop => Request::Shutdown,
Command::Now(args) => {
let format = args.format;
let exit_code = match run_now(&endpoint, args).await {
@@ -1119,19 +1142,72 @@ fn write_screenshot(width: u16, height: u16, png: &[u8], path: &Path) -> anyhow:
Ok(())
}
#[cfg(unix)]
fn endpoint_from_arg(arg: Option<String>) -> Endpoint {
fn endpoint_from_arg(arg: Option<String>, backend: Backend) -> Endpoint {
match arg {
Some(value) => Endpoint(PathBuf::from(value)),
None => transport::default_endpoint(),
Some(value) => transport::endpoint_from_string(value),
None => match backend {
Backend::Daemon => transport::default_endpoint_named("ironrdp-agent"),
Backend::Viewer => transport::default_endpoint_named("ironrdp-viewer"),
},
}
}
#[cfg(windows)]
fn endpoint_from_arg(arg: Option<String>) -> Endpoint {
match arg {
Some(value) => Endpoint(value),
None => transport::default_endpoint(),
async fn ensure_backend(endpoint: &Endpoint, backend: Backend) -> anyhow::Result<()> {
if transport::send_request(endpoint, &Request::Status).await.is_ok() {
return Ok(());
}
let mut child = spawn_backend(endpoint, backend)?;
let deadline = Instant::now() + StdDuration::from_secs(10);
loop {
if transport::send_request(endpoint, &Request::Status).await.is_ok() {
return Ok(());
}
if let Some(status) = child.try_wait().context("check RPC backend process")? {
anyhow::bail!(
"{} backend exited before becoming ready with status {status}",
backend_name(backend)
);
}
if Instant::now() >= deadline {
anyhow::bail!("timed out waiting for {} backend at {endpoint}", backend_name(backend));
}
tokio::time::sleep(StdDuration::from_millis(50)).await;
}
}
fn spawn_backend(endpoint: &Endpoint, backend: Backend) -> anyhow::Result<std::process::Child> {
let endpoint = endpoint.to_string();
let mut command = match backend {
Backend::Daemon => {
let executable = std::env::current_exe().context("resolve ironrdp-agent executable")?;
let mut command = ProcessCommand::new(executable);
command.args(["--endpoint", &endpoint, "daemon-start"]);
command
}
Backend::Viewer => {
let mut executable = std::env::current_exe().context("resolve ironrdp-agent executable")?;
executable.set_file_name(format!("ironrdp-viewer{}", std::env::consts::EXE_SUFFIX));
let mut command = ProcessCommand::new(executable);
command.args(["--rpc", "--rpc-endpoint", &endpoint]);
command
}
};
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("start {} backend", backend_name(backend)))
}
fn backend_name(backend: Backend) -> &'static str {
match backend {
Backend::Daemon => "daemon",
Backend::Viewer => "viewer",
}
}
@@ -1203,7 +1279,21 @@ fn property_description(key: &str) -> Option<&'static str> {
mod tests {
use clap::Parser as _;
use super::{Cli, CommonExecutionArgs, NowExecutionKind, build_now_execution};
use super::{Backend, Cli, CommonExecutionArgs, NowExecutionKind, build_now_execution, endpoint_from_arg};
#[test]
fn backend_endpoint_selection_is_distinct_and_overridable() {
let daemon = endpoint_from_arg(None, Backend::Daemon).to_string();
let viewer = endpoint_from_arg(None, Backend::Viewer).to_string();
assert_ne!(daemon, viewer);
assert!(daemon.contains("ironrdp-agent"));
assert!(viewer.contains("ironrdp-viewer"));
assert_eq!(
endpoint_from_arg(Some("custom-rpc-endpoint".to_owned()), Backend::Viewer).to_string(),
"custom-rpc-endpoint"
);
}
#[test]
fn shell_is_not_an_agent_command() {
+142 -35
View File
@@ -33,32 +33,21 @@ use crate::transport::{Endpoint, Listener, read_message, write_message};
/// (overlay wins), so any setting — credentials in particular — can be preconfigured without the
/// caller ever supplying it. Pass an empty set when no overlay is desired.
pub async fn run(endpoint: Endpoint, overlay: PropertySet) -> anyhow::Result<()> {
// On Unix a leftover socket file would make `bind` fail; clear it if no daemon is alive.
#[cfg(unix)]
if endpoint.0.exists() {
if crate::transport::connect(&endpoint).await.is_ok() {
anyhow::bail!("a daemon already appears to be running at {endpoint}");
}
// No daemon answered, so the path is a stale socket we can reclaim. Guard against deleting
// an unrelated regular file (or following a symlink) when `--endpoint` points elsewhere:
// inspect the path itself and only remove genuine sockets.
use std::os::unix::fs::FileTypeExt as _;
let metadata =
std::fs::symlink_metadata(&endpoint.0).with_context(|| format!("stat IPC endpoint {endpoint}"))?;
if !metadata.file_type().is_socket() {
anyhow::bail!("refusing to remove {endpoint}: path exists and is not a socket");
}
std::fs::remove_file(&endpoint.0).with_context(|| format!("remove stale socket {endpoint}"))?;
}
init_daemon_logging();
let logs = LogBuffer::new();
let daemon = Arc::new(Daemon::with_overlay(overlay));
serve(endpoint, daemon).await
}
/// Serves `daemon` on `endpoint` until a [`Request::Shutdown`] is received.
///
/// The caller owns the daemon so it can share the same session state with another frontend, such
/// as the viewer window.
pub async fn serve(endpoint: Endpoint, daemon: Arc<Daemon>) -> anyhow::Result<()> {
crate::transport::prepare_endpoint(&endpoint).await?;
let mut listener = Listener::bind(&endpoint).with_context(|| format!("bind IPC endpoint {endpoint}"))?;
let daemon = Arc::new(Daemon::new(logs, overlay));
info!(%endpoint, "Daemon listening");
let mut shutdown = daemon.shutdown_receiver();
loop {
tokio::select! {
result = listener.accept() => {
@@ -70,21 +59,29 @@ pub async fn run(endpoint: Endpoint, overlay: PropertySet) -> anyhow::Result<()>
}
});
}
_ = tokio::signal::ctrl_c() => {
result = tokio::signal::ctrl_c() => {
result.context("wait for shutdown signal")?;
info!("Received shutdown signal, stopping");
break;
}
result = shutdown.changed() => {
result.context("wait for RPC shutdown")?;
info!("Received RPC shutdown request, stopping");
break;
}
}
}
Ok(())
}
async fn handle_connection<S>(mut stream: S, daemon: &Daemon) -> anyhow::Result<()>
/// Handles one framed RPC request and writes its response, including streamed NOW events.
pub async fn handle_connection<S>(mut stream: S, daemon: &Daemon) -> anyhow::Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let request: Request = read_message(&mut stream).await?;
let shutdown = matches!(&request, Request::Shutdown);
trace!(?request, "Handling IPC request");
let response = daemon.handle(request).await;
trace!(ok = response.response().is_ok(), "Replying to IPC request");
@@ -100,10 +97,13 @@ where
}
}
}
if shutdown {
daemon.signal_shutdown();
}
Ok(())
}
enum DaemonResponse {
pub enum DaemonResponse {
Single(Response),
Stream(Response, OperationAttachment),
}
@@ -117,7 +117,7 @@ impl DaemonResponse {
}
/// The daemon's mutable state: the (single) current session, plus the shared log buffer.
struct Daemon {
pub struct Daemon {
state: Mutex<Option<Session>>,
/// Serializes synchronous RDP session construction so concurrent IPC `connect` requests cannot
/// both observe an empty session slot before either one installs its session.
@@ -129,6 +129,9 @@ struct Daemon {
/// Whether [`Self::overlay`] contributes any secret (password/token) value, i.e. whether the
/// caller can omit credentials of its own.
credentials_loaded: bool,
/// Notifies an optional GUI frontend whenever retained live state changes.
notification: Option<mpsc::UnboundedSender<()>>,
shutdown: tokio::sync::watch::Sender<()>,
}
/// Per-session state owned by the request handler.
@@ -154,10 +157,11 @@ struct Live {
/// A decoded frame retained for screenshots. `pixels` are `0x00RRGGBB` (`to_be_bytes()` yields
/// `[0, R, G, B]`), row-major, `width * height` entries, with the remote cursor blended in.
struct Frame {
width: u16,
height: u16,
pixels: Vec<u32>,
#[derive(Clone)]
pub struct Frame {
pub width: u16,
pub height: u16,
pub pixels: Vec<u32>,
}
impl Daemon {
@@ -165,22 +169,56 @@ impl Daemon {
// Credentials are considered "loaded" when the overlay provides at least one secret value,
// which is what frees the caller from supplying a password.
let credentials_loaded = overlay.iter().any(|(key, _)| ironrdp_cfg::is_secret_key(key));
let (shutdown, _) = tokio::sync::watch::channel(());
Self {
state: Mutex::new(None),
connect_lock: Mutex::new(()),
logs,
overlay,
credentials_loaded,
notification: None,
shutdown,
}
}
async fn handle(&self, request: Request) -> DaemonResponse {
/// Creates a daemon with no preconfigured connection properties.
pub fn with_overlay(overlay: PropertySet) -> Self {
Self::new(LogBuffer::new(), overlay)
}
/// Adds a notification channel for frontends that render the retained session state.
#[must_use]
pub fn with_notification(mut self, notification: mpsc::UnboundedSender<()>) -> Self {
self.notification = Some(notification);
self
}
/// Returns a receiver that is notified when the server should stop.
pub fn shutdown_receiver(&self) -> tokio::sync::watch::Receiver<()> {
self.shutdown.subscribe()
}
/// Returns the latest cursor-composited framebuffer, if one is available.
///
/// # Panics
///
/// Panics if the daemon or session state mutex is poisoned.
pub fn current_frame(&self) -> Option<Frame> {
let guard = self.state.lock().expect("daemon state poisoned");
guard
.as_ref()
.and_then(|session| session.live.lock().expect("session live state poisoned").frame.clone())
}
/// Handles one typed RPC request.
pub async fn handle(&self, request: Request) -> DaemonResponse {
match request {
Request::Connect {
properties,
log_directive,
} => DaemonResponse::Single(self.connect(properties, log_directive)),
Request::Disconnect => DaemonResponse::Single(self.disconnect()),
Request::Shutdown => DaemonResponse::Single(Self::shutdown()),
Request::Status => DaemonResponse::Single(self.status()),
Request::QueryProps { filter } => DaemonResponse::Single(self.query_props(filter.as_ref())),
Request::QueryLogs { substring, last } => {
@@ -370,7 +408,7 @@ impl Daemon {
);
}
tokio::spawn(consume_output(output_rx, Arc::clone(&live)));
tokio::spawn(consume_output(output_rx, Arc::clone(&live), self.notification.clone()));
info!(%destination, "Started RDP session");
@@ -386,7 +424,12 @@ impl Daemon {
Response::ok()
}
fn disconnect(&self) -> Response {
/// Requests the active RDP session to disconnect.
///
/// # Panics
///
/// Panics if the daemon or session state mutex is poisoned.
pub fn disconnect(&self) -> Response {
let mut guard = self.state.lock().expect("daemon state poisoned");
match guard.as_mut() {
None => {
@@ -512,7 +555,12 @@ impl Daemon {
}
}
fn resize(&self, width: u16, height: u16) -> Response {
/// Sends a resize event to the active RDP session.
///
/// # Panics
///
/// Panics if the daemon state mutex is poisoned.
pub fn resize(&self, width: u16, height: u16) -> Response {
if width == 0 || height == 0 {
return Response::typed_error(
crate::ipc::AgentErrorCategory::InvalidRequest,
@@ -538,7 +586,12 @@ impl Daemon {
}
}
fn input(&self, operation: Operation) -> Response {
/// Sends an input operation to the active RDP session.
///
/// # Panics
///
/// Panics if the daemon state mutex is poisoned.
pub fn input(&self, operation: Operation) -> Response {
let mut guard = self.state.lock().expect("daemon state poisoned");
let Some(session) = guard.as_mut() else {
return Response::typed_error(crate::ipc::AgentErrorCategory::Unavailable, "no active session");
@@ -560,6 +613,14 @@ impl Daemon {
Response::ok()
}
fn shutdown() -> Response {
Response::ok()
}
fn signal_shutdown(&self) {
let _ = self.shutdown.send(());
}
fn operations(&self) -> Result<OperationManager, Response> {
self.state
.lock()
@@ -697,7 +758,11 @@ impl Daemon {
}
/// Consumes the bounded output-event stream, keeping the live state current.
async fn consume_output(mut output_rx: mpsc::Receiver<RdpOutputEvent>, live: Arc<Mutex<Live>>) {
async fn consume_output(
mut output_rx: mpsc::Receiver<RdpOutputEvent>,
live: Arc<Mutex<Live>>,
notification: Option<mpsc::UnboundedSender<()>>,
) {
while let Some(event) = output_rx.recv().await {
let mut guard = live.lock().expect("session live state poisoned");
let previous = guard.state;
@@ -745,6 +810,10 @@ async fn consume_output(mut output_rx: mpsc::Receiver<RdpOutputEvent>, live: Arc
// above; the remaining pointer events (default/hidden) carry no live state we track.
_ => {}
}
drop(guard);
if let Some(notification) = &notification {
let _ = notification.send(());
}
}
// The engine thread has ended (channel closed). Resolve any transient state so a subsequent
@@ -756,6 +825,10 @@ async fn consume_output(mut output_rx: mpsc::Receiver<RdpOutputEvent>, live: Arc
) {
guard.state = ConnState::Disconnected;
}
drop(guard);
if let Some(notification) = &notification {
let _ = notification.send(());
}
}
/// Encodes a retained framebuffer to PNG bytes.
@@ -832,3 +905,37 @@ fn current_platform() -> MajorPlatformType {
_ => MajorPlatformType::UNSPECIFIED,
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{Daemon, handle_connection};
use crate::ipc::{Payload, Request, Response};
use crate::transport::{read_message, write_message};
use ironrdp_propertyset::PropertySet;
#[tokio::test]
async fn shutdown_reply_is_written_before_server_signal() {
let daemon = Arc::new(Daemon::with_overlay(PropertySet::new()));
let mut shutdown = daemon.shutdown_receiver();
let (mut client, server) = tokio::io::duplex(4096);
let handler_daemon = Arc::clone(&daemon);
let handler = tokio::spawn(async move { handle_connection(server, handler_daemon.as_ref()).await });
write_message(&mut client, &Request::Shutdown)
.await
.expect("write shutdown request");
let response: Response = read_message(&mut client).await.expect("read shutdown response");
assert_eq!(response, Response::Ok(Payload::Empty));
tokio::time::timeout(core::time::Duration::from_secs(1), shutdown.changed())
.await
.expect("shutdown signal timeout")
.expect("shutdown signal");
handler
.await
.expect("join shutdown handler")
.expect("handle shutdown request");
}
}
+20 -7
View File
@@ -3,20 +3,25 @@
/// Structured guide printed by `ironrdp-agent --help-agent`.
pub(crate) const AGENT_GUIDE: &str = r#"# ironrdp-agent
A CLI-driven, daemon-backed RDP client. One binary plays two roles:
A CLI-driven RDP client. One binary provides a short-lived CLI for two local RPC backends:
- DAEMON: `ironrdp-agent daemon-start` runs a long-lived foreground process that owns the RDP
engine and one RDP session. Background it yourself (e.g. `ironrdp-agent daemon-start &`).
- CLI: every other subcommand opens the local IPC endpoint, sends one request, prints the
response, and exits.
- VIEWER: `ironrdp-viewer --rpc` runs the same RPC server alongside the visible viewer window.
- CLI: every operation opens the selected local IPC endpoint, sends one request, prints the response,
and exits.
The daemon stays alive across CLI invocations. One daemon serves one RDP session.
The daemon is the default backend. Normal operations automatically start the selected backend when
it is not already running, then reuse it across CLI invocations. One backend serves one RDP session.
## Endpoint
Unix: `$XDG_RUNTIME_DIR/ironrdp-agent-<uid>.sock` (falls back to `/tmp/ironrdp-agent-<uid>.sock`).
Windows: `\\.\pipe\ironrdp-agent-<user>`.
Override with `--endpoint <PATH-OR-PIPE>` on any subcommand.
`--backend daemon` (the default): Unix `$XDG_RUNTIME_DIR/ironrdp-agent-<uid>.sock` (falls back to
`/tmp/ironrdp-agent-<uid>.sock`); Windows `\\.\pipe\ironrdp-agent-<user>`.
`--backend viewer`: Unix `$XDG_RUNTIME_DIR/ironrdp-viewer-<uid>.sock` (falls back to
`/tmp/ironrdp-viewer-<uid>.sock`); Windows `\\.\pipe\ironrdp-viewer-<user>`.
Override with `--endpoint <PATH-OR-PIPE>` on any agent subcommand. A manually started viewer accepts
`--rpc-endpoint <PATH-OR-PIPE>`.
## Lifecycle
@@ -30,6 +35,14 @@ Override with `--endpoint <PATH-OR-PIPE>` on any subcommand.
file line (TYPE is `i` for integer or `s` for string), e.g.
`--prop ironrdp_autologon:i:1`. Check `status` to see whether
credentials are already loaded before supplying any yourself.
- `--backend viewer <operation>`
Drive a visible `ironrdp-viewer` RPC host instead of the daemon.
The viewer is started automatically for normal operations and
remains available for later commands; the GUI and CLI share one
RDP session.
- `stop`
Stop the selected long-lived backend after replying. This does
not start a backend that is not already running.
- `connect [--rdp-file F] [--prop KEY:TYPE:VALUE]... [--server H[:PORT]] [-u USER] [-p PASS] [-d DOMAIN] [--log-directive D]`
Merge an optional .rdp file with CLI overrides into one config and
open a session. Precedence (low to high): .rdp file -> `--prop`
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -24,6 +24,4 @@ pub(crate) mod logbuf;
// so they can be unit tested from the workspace test suite.
#[cfg(feature = "internal")]
#[doc(hidden)]
pub mod wire;
#[cfg(not(feature = "internal"))]
pub(crate) mod wire;
pub use ironrdp_rpc::wire;
+2 -495
View File
@@ -1,496 +1,3 @@
//! Local IPC transport and message framing.
//!
//! The daemon and CLI talk over a platform-native local transport:
//!
//! - **Unix**: a [`tokio::net::UnixListener`]/[`tokio::net::UnixStream`] at
//! `$XDG_RUNTIME_DIR/ironrdp-agent-<uid>.sock`, falling back to `/tmp/ironrdp-agent-<uid>.sock`
//! when `XDG_RUNTIME_DIR` is unset.
//! - **Windows**: a named pipe at `\\.\pipe\ironrdp-agent-<user>`, restricted to the current user.
//!
//! Framing is identical on both: a little-endian `u32` byte-count prefix followed by the `Encode`d
//! message body.
//! Compatibility re-export for the shared local RPC transport.
use anyhow::{Context as _, bail};
use ironrdp_core::{DecodeOwned, Encode};
use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
use crate::ipc::{Request, Response};
/// Upper bound on a single framed message, guarding against absurd length prefixes.
const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024;
/// Writes `message` to `stream`, length-delimited.
pub(crate) async fn write_message<S, M>(stream: &mut S, message: &M) -> anyhow::Result<()>
where
S: AsyncWrite + Unpin,
M: Encode,
{
let body = ironrdp_core::encode_vec(message).map_err(|e| anyhow::anyhow!("encode {}: {e}", message.name()))?;
let len = u32::try_from(body.len()).context("message too large to frame")?;
stream
.write_all(&len.to_le_bytes())
.await
.context("write frame length")?;
stream.write_all(&body).await.context("write frame body")?;
stream.flush().await.context("flush frame")?;
Ok(())
}
/// Reads a single length-delimited message from `stream`.
pub(crate) async fn read_message<S, M>(stream: &mut S) -> anyhow::Result<M>
where
S: AsyncRead + Unpin,
M: DecodeOwned,
{
let mut len_buf = [0u8; 4];
stream.read_exact(&mut len_buf).await.context("read frame length")?;
let len = usize::try_from(u32::from_le_bytes(len_buf)).expect("u32 fits in usize on supported platforms");
if MAX_MESSAGE_LEN < len {
bail!("frame length {len} exceeds the {MAX_MESSAGE_LEN}-byte limit");
}
let mut body = vec![0u8; len];
stream.read_exact(&mut body).await.context("read frame body")?;
ironrdp_core::decode_owned(&body).map_err(|e| anyhow::anyhow!("decode: {e}"))
}
/// Opens the endpoint, sends one `request`, and returns the daemon's `Response`.
pub async fn send_request(endpoint: &Endpoint, request: &Request) -> anyhow::Result<Response> {
let mut stream = open_stream(endpoint, request).await?;
read_message(&mut stream).await
}
/// Opens an IPC connection, sends `request`, and leaves the stream available for streamed replies.
pub async fn open_stream(endpoint: &Endpoint, request: &Request) -> anyhow::Result<ClientStream> {
let mut stream = connect(endpoint)
.await
.with_context(|| format!("connect to daemon at {endpoint}"))?;
write_message(&mut stream, request).await?;
Ok(stream)
}
#[cfg(unix)]
mod imp {
use std::io;
use std::path::PathBuf;
use tokio::net::{UnixListener, UnixStream};
/// A resolved IPC endpoint (a Unix domain socket path).
#[derive(Debug, Clone)]
pub struct Endpoint(pub PathBuf);
impl core::fmt::Display for Endpoint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0.display())
}
}
/// Returns the default per-user endpoint.
pub fn default_endpoint() -> Endpoint {
// SAFETY: `getuid` has no preconditions and is always safe to call.
let uid = unsafe { libc::getuid() };
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/tmp"));
Endpoint(dir.join(format!("ironrdp-agent-{uid}.sock")))
}
/// Connects to a listening daemon.
pub async fn connect(endpoint: &Endpoint) -> io::Result<UnixStream> {
UnixStream::connect(&endpoint.0).await
}
/// A bound listener that accepts client connections.
pub struct Listener {
inner: UnixListener,
path: PathBuf,
}
impl Listener {
/// Binds the listener at `endpoint`.
pub fn bind(endpoint: &Endpoint) -> io::Result<Self> {
let inner = UnixListener::bind(&endpoint.0)?;
// Restrict the socket to the owner. The fallback directory is world-writable `/tmp`, so
// without this any local user could connect and drive the session (input, screenshots,
// logs). Fail loudly rather than serve on a world-accessible endpoint.
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(&endpoint.0, std::fs::Permissions::from_mode(0o600))?;
Ok(Self {
inner,
path: endpoint.0.clone(),
})
}
/// Accepts the next client connection.
pub async fn accept(&mut self) -> io::Result<UnixStream> {
let (stream, _addr) = self.inner.accept().await?;
Ok(stream)
}
}
impl Drop for Listener {
fn drop(&mut self) {
// Best-effort removal of the socket file on shutdown (named pipes need no cleanup).
let _ = std::fs::remove_file(&self.path);
}
}
}
#[cfg(windows)]
mod imp {
use std::io;
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions};
use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
use windows::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows::Win32::Security::{
GetTokenInformation, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
use windows::core::{PCWSTR, PWSTR};
/// A resolved IPC endpoint (a named pipe path).
#[derive(Debug, Clone)]
pub struct Endpoint(pub String);
impl core::fmt::Display for Endpoint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Returns the default per-user endpoint.
pub fn default_endpoint() -> Endpoint {
let user = whoami::username().unwrap_or_else(|_| "user".to_owned());
Endpoint(format!(r"\\.\pipe\ironrdp-agent-{user}"))
}
/// Connects to a listening daemon.
pub async fn connect(endpoint: &Endpoint) -> io::Result<NamedPipeClient> {
ClientOptions::new().open(&endpoint.0)
}
/// Owns a process token handle and closes it on drop.
struct OwnedTokenHandle(HANDLE);
impl Drop for OwnedTokenHandle {
fn drop(&mut self) {
// SAFETY: `self.0` is a real token handle from `OpenProcessToken`, owned exclusively by us.
if let Err(e) = unsafe { CloseHandle(self.0) } {
tracing::warn!(error = %e, "Failed to close process token handle");
}
}
}
/// Owns a self-relative security descriptor allocated by
/// `ConvertStringSecurityDescriptorToSecurityDescriptorW` and frees it with `LocalFree` on drop.
struct OwnedSecurityDescriptor(PSECURITY_DESCRIPTOR);
impl OwnedSecurityDescriptor {
/// Builds a security descriptor granting access only to the current user.
///
/// The descriptor is a protected DACL (no inherited ACEs) with a single allow-ACE granting
/// `GENERIC_ALL` to the user identified by the current process token. This mirrors the Unix
/// listener's `0o600` owner-only stance: only the user running the daemon may connect to the
/// named pipe. On shared Windows hosts the pipe namespace is otherwise reachable by every
/// local user, so this is the last line of defense against a different local user driving the
/// session (input, screenshots, logs, NOW execution).
fn for_current_user() -> io::Result<Self> {
let buffer = current_user_token_buffer()?;
let sid = sid_from_token_buffer(&buffer);
let mut sid_wide = PWSTR(core::ptr::null_mut());
// SAFETY: `sid` is a valid SID from the token; `sid_wide` is a valid out-pointer.
unsafe { ConvertSidToStringSidW(sid, core::ptr::addr_of_mut!(sid_wide)) }
.map_err(|e| io::Error::other(format!("convert sid to string: {e}")))?;
// SAFETY: `sid_wide` points to a null-terminated UTF-16 string allocated by the call above.
let sid_text =
unsafe { sid_wide.to_string() }.map_err(|e| io::Error::other(format!("decode sid string: {e}")))?;
// SAFETY: `sid_wide` was `LocalAlloc`'d by `ConvertSidToStringSidW` and is no longer needed.
let _ = unsafe { LocalFree(Some(HLOCAL(sid_wide.as_ptr().cast::<core::ffi::c_void>()))) };
// Build the SDDL: a protected DACL granting GENERIC_ALL to the current user only.
let sddl_string = format!("D:P(A;;GA;;;{sid_text})");
let mut sddl_utf16: Vec<u16> = sddl_string.encode_utf16().collect();
sddl_utf16.push(0u16);
let sddl_ptr = PCWSTR::from_raw(sddl_utf16.as_ptr());
let mut security_descriptor = PSECURITY_DESCRIPTOR(core::ptr::null_mut());
// SAFETY: `sddl_ptr` is a valid null-terminated SDDL string; `SDDL_REVISION_1` is the only
// supported revision; `security_descriptor` is a valid out-pointer. The returned SD is
// `LocalAlloc`'d and owned by us.
unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl_ptr,
SDDL_REVISION_1,
core::ptr::addr_of_mut!(security_descriptor),
None,
)
}
.map_err(|e| io::Error::other(format!("convert sddl to security descriptor: {e}")))?;
Ok(Self(security_descriptor))
}
/// Returns the raw security-descriptor pointer for use as `lpSecurityDescriptor`.
fn as_ptr(&self) -> *mut core::ffi::c_void {
self.0.0
}
}
impl Drop for OwnedSecurityDescriptor {
fn drop(&mut self) {
// SAFETY: `self.0` is a self-relative SD allocated by
// `ConvertStringSecurityDescriptorToSecurityDescriptorW` (via `LocalAlloc`) and owned
// exclusively by this guard.
let _ = unsafe { LocalFree(Some(HLOCAL(self.0.0))) };
}
}
/// Returns the buffer holding the `TOKEN_USER` of the current process token.
///
/// The user SID is referenced by `TOKEN_USER.User.Sid` and lives inside this buffer, so keep the
/// buffer alive while using the SID pointer.
fn current_user_token_buffer() -> io::Result<Vec<u8>> {
// SAFETY: `GetCurrentProcess` has no preconditions and returns a pseudo-handle that must
// not be closed.
let process = unsafe { GetCurrentProcess() };
let mut token = HANDLE::default();
// SAFETY: `process` is the valid current-process pseudo-handle; `token` is a valid out-pointer.
unsafe { OpenProcessToken(process, TOKEN_QUERY, core::ptr::addr_of_mut!(token)) }
.map_err(|e| io::Error::other(format!("open process token: {e}")))?;
let token_guard = OwnedTokenHandle(token);
let token = token_guard.0;
// First query the required buffer size; the call fails with `ERROR_INSUFFICIENT_BUFFER`.
let mut len = 0u32;
// SAFETY: `token` is a valid token handle; a null buffer with zero length is the documented
// way to retrieve the required size; `len` is a valid out-pointer.
let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, core::ptr::addr_of_mut!(len)) };
let mut buffer = vec![0u8; usize::try_from(len).expect("token information length fits in usize")];
// SAFETY: `token` is valid; `buffer` has `len` bytes as required; `len` is a valid out-pointer.
unsafe {
GetTokenInformation(
token,
TokenUser,
Some(buffer.as_mut_ptr().cast::<core::ffi::c_void>()),
len,
core::ptr::addr_of_mut!(len),
)
}
.map_err(|e| io::Error::other(format!("query token user: {e}")))?;
Ok(buffer)
}
/// Returns the user SID referenced by a token buffer from [`current_user_token_buffer`].
fn sid_from_token_buffer(buffer: &[u8]) -> PSID {
// The buffer is byte-aligned, so read the `TOKEN_USER` header unaligned; the SID it references
// lives further inside the buffer and stays valid as long as the buffer does.
// SAFETY: `GetTokenInformation` wrote a valid `TOKEN_USER` at the start of `buffer`.
let token_user = unsafe { core::ptr::read_unaligned(buffer.as_ptr().cast::<TOKEN_USER>()) };
token_user.User.Sid
}
/// Creates one named-pipe server instance with `security` applied as its security descriptor.
///
/// `CreateNamedPipeW` copies the security descriptor before returning, so `security` may be
/// reused across instances and need only outlive this synchronous call. `first` sets
/// `FILE_FLAG_FIRST_PIPE_INSTANCE`, which is only valid for the first instance of a pipe name.
fn create_server_instance(
name: &str,
first: bool,
security: &OwnedSecurityDescriptor,
) -> io::Result<NamedPipeServer> {
let mut options = ServerOptions::new();
if first {
options.first_pipe_instance(true);
}
let mut attributes = SECURITY_ATTRIBUTES {
nLength: u32::try_from(size_of::<SECURITY_ATTRIBUTES>()).expect("security_attributes struct fits in u32"),
lpSecurityDescriptor: security.as_ptr(),
..Default::default()
};
let raw = core::ptr::addr_of_mut!(attributes).cast::<core::ffi::c_void>();
// SAFETY: `attributes` lives for the duration of this synchronous call; `CreateNamedPipeW`
// copies the security descriptor before returning, so dropping `attributes` afterwards is safe.
unsafe { options.create_with_security_attributes_raw(name, raw) }
}
/// A named-pipe listener.
///
/// It always keeps one ready (unconnected) server instance alive, which is both what serves the
/// next connection and what upholds the `first_pipe_instance` exclusivity (a pipe with no live
/// instance would let a second daemon claim the name). Every instance is created with a security
/// descriptor that restricts access to the current user, mirroring the Unix listener's `0o600`.
pub struct Listener {
name: String,
ready: NamedPipeServer,
security: OwnedSecurityDescriptor,
}
impl Listener {
/// Creates the first pipe instance, claiming the name exclusively.
///
/// `first_pipe_instance(true)` makes this fail with `ERROR_ACCESS_DENIED` if another daemon
/// already owns the pipe, so two daemons cannot coexist on the same endpoint.
pub fn bind(endpoint: &Endpoint) -> io::Result<Self> {
let security = OwnedSecurityDescriptor::for_current_user()?;
let ready = create_server_instance(&endpoint.0, true, &security)?;
Ok(Self {
name: endpoint.0.clone(),
ready,
security,
})
}
/// Waits for the next client to connect to the ready instance, then mints a replacement.
pub async fn accept(&mut self) -> io::Result<NamedPipeServer> {
// Connect by reference so a cancelled future leaves `ready` intact (and the pipe alive).
self.ready.connect().await?;
// Mint the next listening instance before returning so the pipe is never instance-less.
// Subsequent instances must omit `first_pipe_instance`, which is only valid on the first.
let next = create_server_instance(&self.name, false, &self.security)?;
Ok(core::mem::replace(&mut self.ready, next))
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows::Win32::Foundation::ERROR_SUCCESS;
use windows::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
use windows::Win32::Security::{
ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, AclSizeInformation, DACL_SECURITY_INFORMATION, EqualSid,
GetAce, GetAclInformation, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, SE_DACL_PROTECTED,
};
/// The pipe created by the listener must actually carry the restrictive DACL, not just a
/// non-null descriptor. This catches three regressions a non-null check would miss: the SDDL
/// granting `Everyone`, the protected-DACL flag (`P`) being dropped, and `create_server_instance`
/// failing to apply the descriptor. It queries the live pipe's DACL and asserts it is
/// protected and contains exactly one allow-ACE granting `GENERIC_ALL` to the current user SID.
#[tokio::test]
async fn pipe_dacl_grants_generic_all_only_to_current_user() {
// Expected SID = current process user.
let expected_buffer = current_user_token_buffer().expect("get current user token");
let expected_sid = sid_from_token_buffer(&expected_buffer);
// Build the descriptor and a real server instance with a unique name.
let security = OwnedSecurityDescriptor::for_current_user().expect("build security descriptor");
let name = format!("\\\\.\\pipe\\ironrdp-agent-acl-test-{}", std::process::id());
let mut name_utf16: Vec<u16> = name.encode_utf16().collect();
name_utf16.push(0u16);
let _server = create_server_instance(&name, true, &security).expect("create pipe instance");
// Query the pipe's actual DACL.
let mut sd = PSECURITY_DESCRIPTOR(core::ptr::null_mut());
let mut dacl: *mut ACL = core::ptr::null_mut();
// SAFETY: `name_utf16` is a valid null-terminated pipe path; we request only the DACL; the
// out-pointers are valid. The returned SD is `LocalAlloc`'d and owned by us until freed below.
let result = unsafe {
GetNamedSecurityInfoW(
PCWSTR::from_raw(name_utf16.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(core::ptr::addr_of_mut!(dacl)),
None,
core::ptr::addr_of_mut!(sd),
)
};
assert_eq!(result, ERROR_SUCCESS, "GetNamedSecurityInfoW should succeed");
// `GetNamedSecurityInfoW` `LocalAlloc`'s the descriptor; reuse the production RAII guard so it
// is freed on drop at the end of the test even if an assertion below panics.
let _sd_guard = OwnedSecurityDescriptor(sd);
// The DACL must be protected (no inherited ACEs from the pipe namespace).
let mut control: u16 = 0;
let mut revision: u32 = 0;
// SAFETY: `sd` is a valid self-relative SD returned by `GetNamedSecurityInfoW`.
unsafe {
GetSecurityDescriptorControl(sd, core::ptr::addr_of_mut!(control), core::ptr::addr_of_mut!(revision))
}
.expect("get security descriptor control");
assert!(
(control & SE_DACL_PROTECTED.0) != 0,
"DACL must be protected so inherited ACEs cannot widen access"
);
// Exactly one ACE must be present.
let mut dacl_present = windows::core::BOOL::default();
let mut dacl_ptr: *mut ACL = core::ptr::null_mut();
let mut defaulted = windows::core::BOOL::default();
// SAFETY: `sd` is a valid SD; the out-pointers are valid.
unsafe {
GetSecurityDescriptorDacl(
sd,
core::ptr::addr_of_mut!(dacl_present),
core::ptr::addr_of_mut!(dacl_ptr),
core::ptr::addr_of_mut!(defaulted),
)
}
.expect("get dacl");
assert!(dacl_present.as_bool(), "DACL must be present");
assert!(!dacl_ptr.is_null(), "DACL pointer must not be null");
let mut size_info = ACL_SIZE_INFORMATION::default();
// SAFETY: `dacl_ptr` is a valid ACL; `size_info` is a valid out-buffer of the right size.
unsafe {
GetAclInformation(
dacl_ptr.cast_const(),
core::ptr::addr_of_mut!(size_info).cast::<core::ffi::c_void>(),
u32::try_from(size_of::<ACL_SIZE_INFORMATION>()).expect("acl size information fits in u32"),
AclSizeInformation,
)
}
.expect("get acl information");
assert_eq!(size_info.AceCount, 1, "DACL must contain exactly one ACE");
// The single ACE must be an allow-ACE granting GENERIC_ALL to the current user SID.
let mut ace_ptr: *mut core::ffi::c_void = core::ptr::null_mut();
// SAFETY: `dacl_ptr` is valid and holds one ACE (verified above); `ace_ptr` is a valid out-pointer.
unsafe { GetAce(dacl_ptr.cast_const(), 0, core::ptr::addr_of_mut!(ace_ptr)) }.expect("get ace");
assert!(!ace_ptr.is_null(), "ACE pointer must not be null");
// SAFETY: ACE 0 is an `ACCESS_ALLOWED_ACE` (SDDL "A;;" = allow) placed at DWORD alignment by
// the ACL; `read_unaligned` avoids any alignment assumption.
let ace: ACCESS_ALLOWED_ACE = unsafe { core::ptr::read_unaligned(ace_ptr.cast::<ACCESS_ALLOWED_ACE>()) };
assert_eq!(
ace.Header.AceType, 0u8, /* ACCESS_ALLOWED_ACE_TYPE */
"ACE must be an allow ACE"
);
// `GENERIC_ALL` (0x10000000) in the SDDL is mapped by the kernel to the file-object-specific
// `FILE_ALL_ACCESS` (0x001F01FF) when the descriptor is stored on a named pipe, so compare
// against the mapped value rather than the generic bit.
assert_eq!(
ace.Mask, 0x001F01FFu32, /* FILE_ALL_ACCESS */
"ACE must grant full access (GENERIC_ALL mapped to the pipe object)"
);
// The SID starts at `SidStart` and extends past the struct into the ACL buffer, so point into
// the in-place ACE rather than the local copy.
// SAFETY: `ace_ptr` is a non-null pointer to a valid `ACCESS_ALLOWED_ACE`; `SidStart` is the
// first DWORD of the variable-length SID that follows the fixed ACE header.
let ace_sid = PSID(unsafe { ace_ptr.byte_add(core::mem::offset_of!(ACCESS_ALLOWED_ACE, SidStart)) });
// SAFETY: both `ace_sid` and `expected_sid` are valid SIDs from the token / ACL.
let sids_equal = unsafe { EqualSid(ace_sid, expected_sid) }.is_ok();
assert!(sids_equal, "ACE SID must equal the current user SID");
}
}
}
pub use imp::{Endpoint, Listener, connect, default_endpoint};
#[cfg(unix)]
pub type ClientStream = tokio::net::UnixStream;
#[cfg(windows)]
pub type ClientStream = tokio::net::windows::named_pipe::NamedPipeClient;
pub use ironrdp_rpc::transport::*;
+19 -2
View File
@@ -69,8 +69,25 @@ fn daemon_reports_no_active_session() {
assert!(stdout.contains("state: NoSession"), "{stdout}");
});
let _ = daemon.kill();
let _ = daemon.wait();
let stop = agent(&endpoint, &["stop"]);
if result.is_ok() {
assert!(stop.status.success(), "{}", String::from_utf8_lossy(&stop.stderr));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if daemon.try_wait().expect("check daemon exit").is_some() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
if daemon.try_wait().expect("check daemon exit").is_none() {
let _ = daemon.kill();
let _ = daemon.wait();
if result.is_ok() {
panic!("daemon did not stop");
}
}
if let Err(error) = result {
std::panic::resume_unwind(error);
+42
View File
@@ -0,0 +1,42 @@
[package]
name = "ironrdp-rpc"
version = "0.1.0"
readme = "README.md"
description = "Shared local RPC protocol and transport for IronRDP clients"
edition.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
authors.workspace = true
keywords.workspace = true
categories.workspace = true
[dependencies]
ironrdp-core = { path = "../ironrdp-core", version = "0.2", features = ["alloc"] }
ironrdp-input = { path = "../ironrdp-input", version = "0.7" }
ironrdp-pdu = { path = "../ironrdp-pdu", version = "0.9" }
ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" }
tokio = { version = "1", features = ["net", "io-util"] }
anyhow = "1"
tracing = "0.1"
[features]
internal = []
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
whoami = "2.1"
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Threading",
] }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt"] }
[lints]
workspace = true
+9
View File
@@ -0,0 +1,9 @@
# IronRDP RPC
Shared local RPC protocol and transport used by `ironrdp-agent` and
`ironrdp-viewer`.
The crate provides the typed request/response schema, binary codecs, framed
messages, Unix-domain-socket transport, and Windows named-pipe transport.
It is an internal workspace crate; both endpoints must use compatible
versions of the protocol.
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
//! Shared local RPC protocol and transport used by the agent and viewer.
pub mod ipc;
pub mod transport;
pub mod wire;
+541
View File
@@ -0,0 +1,541 @@
//! Local IPC transport and message framing.
//!
//! RPC peers talk over a platform-native local transport:
//!
//! - **Unix**: a [`tokio::net::UnixListener`]/[`tokio::net::UnixStream`] at a named
//! `$XDG_RUNTIME_DIR/<name>-<uid>.sock`, falling back to `/tmp` when `XDG_RUNTIME_DIR` is unset.
//! - **Windows**: a named pipe at `\\.\pipe\<name>-<user>`, restricted to the current user.
//!
//! Framing is identical on both: a little-endian `u32` byte-count prefix followed by the `Encode`d
//! message body.
use anyhow::{Context as _, bail};
use ironrdp_core::{DecodeOwned, Encode};
use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
use crate::ipc::{Request, Response};
/// Upper bound on a single framed message, guarding against absurd length prefixes.
const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024;
/// Writes `message` to `stream`, length-delimited.
pub async fn write_message<S, M>(stream: &mut S, message: &M) -> anyhow::Result<()>
where
S: AsyncWrite + Unpin,
M: Encode,
{
let body = ironrdp_core::encode_vec(message).map_err(|e| anyhow::anyhow!("encode {}: {e}", message.name()))?;
let len = u32::try_from(body.len()).context("message too large to frame")?;
stream
.write_all(&len.to_le_bytes())
.await
.context("write frame length")?;
stream.write_all(&body).await.context("write frame body")?;
stream.flush().await.context("flush frame")?;
Ok(())
}
/// Reads a single length-delimited message from `stream`.
pub async fn read_message<S, M>(stream: &mut S) -> anyhow::Result<M>
where
S: AsyncRead + Unpin,
M: DecodeOwned,
{
let mut len_buf = [0u8; 4];
stream.read_exact(&mut len_buf).await.context("read frame length")?;
let len = usize::try_from(u32::from_le_bytes(len_buf)).context("frame length does not fit this platform")?;
if MAX_MESSAGE_LEN < len {
bail!("frame length {len} exceeds the {MAX_MESSAGE_LEN}-byte limit");
}
let mut body = vec![0u8; len];
stream.read_exact(&mut body).await.context("read frame body")?;
ironrdp_core::decode_owned(&body).map_err(|e| anyhow::anyhow!("decode: {e}"))
}
/// Opens the endpoint, sends one `request`, and returns the daemon's `Response`.
pub async fn send_request(endpoint: &Endpoint, request: &Request) -> anyhow::Result<Response> {
let mut stream = open_stream(endpoint, request).await?;
read_message(&mut stream).await
}
/// Opens an IPC connection, sends `request`, and leaves the stream available for streamed replies.
pub async fn open_stream(endpoint: &Endpoint, request: &Request) -> anyhow::Result<ClientStream> {
let mut stream = connect(endpoint)
.await
.with_context(|| format!("connect to RPC server at {endpoint}"))?;
write_message(&mut stream, request).await?;
Ok(stream)
}
#[cfg(unix)]
mod imp {
use anyhow::{Context as _, bail};
use std::io;
use std::path::PathBuf;
use tokio::net::{UnixListener, UnixStream};
/// A resolved IPC endpoint (a Unix domain socket path).
#[derive(Debug, Clone)]
pub struct Endpoint(pub PathBuf);
impl core::fmt::Display for Endpoint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0.display())
}
}
/// Returns the default agent endpoint.
pub fn default_endpoint() -> Endpoint {
default_endpoint_named("ironrdp-agent")
}
/// Returns a named per-user endpoint.
pub fn default_endpoint_named(name: &str) -> Endpoint {
// SAFETY: `getuid` has no preconditions and is always safe to call.
let uid = unsafe { libc::getuid() };
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/tmp"));
Endpoint(dir.join(format!("{name}-{uid}.sock")))
}
pub fn endpoint_from_string(value: String) -> Endpoint {
Endpoint(PathBuf::from(value))
}
pub async fn prepare_endpoint(endpoint: &Endpoint) -> anyhow::Result<()> {
if !endpoint.0.exists() {
return Ok(());
}
if super::connect(endpoint).await.is_ok() {
bail!("an RPC server already appears to be running at {endpoint}");
}
// No server answered, so the path may be a stale socket. Guard against deleting an
// unrelated regular file (or following a symlink) when an explicit endpoint is used.
use std::os::unix::fs::FileTypeExt as _;
let metadata =
std::fs::symlink_metadata(&endpoint.0).with_context(|| format!("stat IPC endpoint {endpoint}"))?;
if !metadata.file_type().is_socket() {
bail!("refusing to remove {endpoint}: path exists and is not a socket");
}
std::fs::remove_file(&endpoint.0).with_context(|| format!("remove stale socket {endpoint}"))?;
Ok(())
}
/// Connects to a listening daemon.
pub async fn connect(endpoint: &Endpoint) -> io::Result<UnixStream> {
UnixStream::connect(&endpoint.0).await
}
/// A bound listener that accepts client connections.
pub struct Listener {
inner: UnixListener,
path: PathBuf,
}
impl Listener {
/// Binds the listener at `endpoint`.
pub fn bind(endpoint: &Endpoint) -> io::Result<Self> {
let inner = UnixListener::bind(&endpoint.0)?;
// Restrict the socket to the owner. The fallback directory is world-writable `/tmp`, so
// without this any local user could connect and drive the session (input, screenshots,
// logs). Fail loudly rather than serve on a world-accessible endpoint.
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(&endpoint.0, std::fs::Permissions::from_mode(0o600))?;
Ok(Self {
inner,
path: endpoint.0.clone(),
})
}
/// Accepts the next client connection.
pub async fn accept(&mut self) -> io::Result<UnixStream> {
let (stream, _addr) = self.inner.accept().await?;
Ok(stream)
}
}
impl Drop for Listener {
fn drop(&mut self) {
// Best-effort removal of the socket file on shutdown (named pipes need no cleanup).
let _ = std::fs::remove_file(&self.path);
}
}
}
#[cfg(windows)]
mod imp {
use std::io;
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions};
use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
use windows::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows::Win32::Security::{
GetTokenInformation, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
use windows::core::{PCWSTR, PWSTR};
/// A resolved IPC endpoint (a named pipe path).
#[derive(Debug, Clone)]
pub struct Endpoint(pub String);
impl core::fmt::Display for Endpoint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Returns the default agent endpoint.
pub fn default_endpoint() -> Endpoint {
default_endpoint_named("ironrdp-agent")
}
/// Returns a named per-user endpoint.
pub fn default_endpoint_named(name: &str) -> Endpoint {
let user = whoami::username().unwrap_or_else(|_| "user".to_owned());
Endpoint(format!(r"\\.\pipe\{name}-{user}"))
}
pub fn endpoint_from_string(value: String) -> Endpoint {
Endpoint(value)
}
pub async fn prepare_endpoint(_endpoint: &Endpoint) -> anyhow::Result<()> {
Ok(())
}
/// Connects to a listening daemon.
pub async fn connect(endpoint: &Endpoint) -> io::Result<NamedPipeClient> {
ClientOptions::new().open(&endpoint.0)
}
/// Owns a process token handle and closes it on drop.
struct OwnedTokenHandle(HANDLE);
impl Drop for OwnedTokenHandle {
fn drop(&mut self) {
// SAFETY: `self.0` is a real token handle from `OpenProcessToken`, owned exclusively by us.
if let Err(e) = unsafe { CloseHandle(self.0) } {
tracing::warn!(error = %e, "Failed to close process token handle");
}
}
}
/// Owns a self-relative security descriptor allocated by
/// `ConvertStringSecurityDescriptorToSecurityDescriptorW` and frees it with `LocalFree` on drop.
struct OwnedSecurityDescriptor(PSECURITY_DESCRIPTOR);
impl OwnedSecurityDescriptor {
/// Builds a security descriptor granting access only to the current user.
///
/// The descriptor is a protected DACL (no inherited ACEs) with a single allow-ACE granting
/// `GENERIC_ALL` to the user identified by the current process token. This mirrors the Unix
/// listener's `0o600` owner-only stance: only the user running the daemon may connect to the
/// named pipe. On shared Windows hosts the pipe namespace is otherwise reachable by every
/// local user, so this is the last line of defense against a different local user driving the
/// session (input, screenshots, logs, NOW execution).
fn for_current_user() -> io::Result<Self> {
let buffer = current_user_token_buffer()?;
let sid = sid_from_token_buffer(&buffer);
let mut sid_wide = PWSTR(core::ptr::null_mut());
// SAFETY: `sid` is a valid SID from the token; `sid_wide` is a valid out-pointer.
unsafe { ConvertSidToStringSidW(sid, core::ptr::addr_of_mut!(sid_wide)) }
.map_err(|e| io::Error::other(format!("convert sid to string: {e}")))?;
// SAFETY: `sid_wide` points to a null-terminated UTF-16 string allocated by the call above.
let sid_text =
unsafe { sid_wide.to_string() }.map_err(|e| io::Error::other(format!("decode sid string: {e}")))?;
// SAFETY: `sid_wide` was `LocalAlloc`'d by `ConvertSidToStringSidW` and is no longer needed.
let _ = unsafe { LocalFree(Some(HLOCAL(sid_wide.as_ptr().cast::<core::ffi::c_void>()))) };
// Build the SDDL: a protected DACL granting GENERIC_ALL to the current user only.
let sddl_string = format!("D:P(A;;GA;;;{sid_text})");
let mut sddl_utf16: Vec<u16> = sddl_string.encode_utf16().collect();
sddl_utf16.push(0u16);
let sddl_ptr = PCWSTR::from_raw(sddl_utf16.as_ptr());
let mut security_descriptor = PSECURITY_DESCRIPTOR(core::ptr::null_mut());
// SAFETY: `sddl_ptr` is a valid null-terminated SDDL string; `SDDL_REVISION_1` is the only
// supported revision; `security_descriptor` is a valid out-pointer. The returned SD is
// `LocalAlloc`'d and owned by us.
unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl_ptr,
SDDL_REVISION_1,
core::ptr::addr_of_mut!(security_descriptor),
None,
)
}
.map_err(|e| io::Error::other(format!("convert sddl to security descriptor: {e}")))?;
Ok(Self(security_descriptor))
}
/// Returns the raw security-descriptor pointer for use as `lpSecurityDescriptor`.
fn as_ptr(&self) -> *mut core::ffi::c_void {
self.0.0
}
}
impl Drop for OwnedSecurityDescriptor {
fn drop(&mut self) {
// SAFETY: `self.0` is a self-relative SD allocated by
// `ConvertStringSecurityDescriptorToSecurityDescriptorW` (via `LocalAlloc`) and owned
// exclusively by this guard.
let _ = unsafe { LocalFree(Some(HLOCAL(self.0.0))) };
}
}
/// Returns the buffer holding the `TOKEN_USER` of the current process token.
///
/// The user SID is referenced by `TOKEN_USER.User.Sid` and lives inside this buffer, so keep the
/// buffer alive while using the SID pointer.
fn current_user_token_buffer() -> io::Result<Vec<u8>> {
// SAFETY: `GetCurrentProcess` has no preconditions and returns a pseudo-handle that must
// not be closed.
let process = unsafe { GetCurrentProcess() };
let mut token = HANDLE::default();
// SAFETY: `process` is the valid current-process pseudo-handle; `token` is a valid out-pointer.
unsafe { OpenProcessToken(process, TOKEN_QUERY, core::ptr::addr_of_mut!(token)) }
.map_err(|e| io::Error::other(format!("open process token: {e}")))?;
let token_guard = OwnedTokenHandle(token);
let token = token_guard.0;
// First query the required buffer size; the call fails with `ERROR_INSUFFICIENT_BUFFER`.
let mut len = 0u32;
// SAFETY: `token` is a valid token handle; a null buffer with zero length is the documented
// way to retrieve the required size; `len` is a valid out-pointer.
let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, core::ptr::addr_of_mut!(len)) };
let mut buffer = vec![0u8; usize::try_from(len).expect("token information length fits in usize")];
// SAFETY: `token` is valid; `buffer` has `len` bytes as required; `len` is a valid out-pointer.
unsafe {
GetTokenInformation(
token,
TokenUser,
Some(buffer.as_mut_ptr().cast::<core::ffi::c_void>()),
len,
core::ptr::addr_of_mut!(len),
)
}
.map_err(|e| io::Error::other(format!("query token user: {e}")))?;
Ok(buffer)
}
/// Returns the user SID referenced by a token buffer from [`current_user_token_buffer`].
fn sid_from_token_buffer(buffer: &[u8]) -> PSID {
// The buffer is byte-aligned, so read the `TOKEN_USER` header unaligned; the SID it references
// lives further inside the buffer and stays valid as long as the buffer does.
// SAFETY: `GetTokenInformation` wrote a valid `TOKEN_USER` at the start of `buffer`.
let token_user = unsafe { core::ptr::read_unaligned(buffer.as_ptr().cast::<TOKEN_USER>()) };
token_user.User.Sid
}
/// Creates one named-pipe server instance with `security` applied as its security descriptor.
///
/// `CreateNamedPipeW` copies the security descriptor before returning, so `security` may be
/// reused across instances and need only outlive this synchronous call. `first` sets
/// `FILE_FLAG_FIRST_PIPE_INSTANCE`, which is only valid for the first instance of a pipe name.
fn create_server_instance(
name: &str,
first: bool,
security: &OwnedSecurityDescriptor,
) -> io::Result<NamedPipeServer> {
let mut options = ServerOptions::new();
if first {
options.first_pipe_instance(true);
}
let mut attributes = SECURITY_ATTRIBUTES {
nLength: u32::try_from(size_of::<SECURITY_ATTRIBUTES>()).expect("security_attributes struct fits in u32"),
lpSecurityDescriptor: security.as_ptr(),
..Default::default()
};
let raw = core::ptr::addr_of_mut!(attributes).cast::<core::ffi::c_void>();
// SAFETY: `attributes` lives for the duration of this synchronous call; `CreateNamedPipeW`
// copies the security descriptor before returning, so dropping `attributes` afterwards is safe.
unsafe { options.create_with_security_attributes_raw(name, raw) }
}
/// A named-pipe listener.
///
/// It always keeps one ready (unconnected) server instance alive, which is both what serves the
/// next connection and what upholds the `first_pipe_instance` exclusivity (a pipe with no live
/// instance would let a second daemon claim the name). Every instance is created with a security
/// descriptor that restricts access to the current user, mirroring the Unix listener's `0o600`.
pub struct Listener {
name: String,
ready: NamedPipeServer,
security: OwnedSecurityDescriptor,
}
impl Listener {
/// Creates the first pipe instance, claiming the name exclusively.
///
/// `first_pipe_instance(true)` makes this fail with `ERROR_ACCESS_DENIED` if another daemon
/// already owns the pipe, so two daemons cannot coexist on the same endpoint.
pub fn bind(endpoint: &Endpoint) -> io::Result<Self> {
let security = OwnedSecurityDescriptor::for_current_user()?;
let ready = create_server_instance(&endpoint.0, true, &security)?;
Ok(Self {
name: endpoint.0.clone(),
ready,
security,
})
}
/// Waits for the next client to connect to the ready instance, then mints a replacement.
pub async fn accept(&mut self) -> io::Result<NamedPipeServer> {
// Connect by reference so a cancelled future leaves `ready` intact (and the pipe alive).
self.ready.connect().await?;
// Mint the next listening instance before returning so the pipe is never instance-less.
// Subsequent instances must omit `first_pipe_instance`, which is only valid on the first.
let next = create_server_instance(&self.name, false, &self.security)?;
Ok(core::mem::replace(&mut self.ready, next))
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows::Win32::Foundation::ERROR_SUCCESS;
use windows::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
use windows::Win32::Security::{
ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, AclSizeInformation, DACL_SECURITY_INFORMATION, EqualSid,
GetAce, GetAclInformation, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, SE_DACL_PROTECTED,
};
/// The pipe created by the listener must actually carry the restrictive DACL, not just a
/// non-null descriptor. This catches three regressions a non-null check would miss: the SDDL
/// granting `Everyone`, the protected-DACL flag (`P`) being dropped, and `create_server_instance`
/// failing to apply the descriptor. It queries the live pipe's DACL and asserts it is
/// protected and contains exactly one allow-ACE granting `GENERIC_ALL` to the current user SID.
#[tokio::test]
async fn pipe_dacl_grants_generic_all_only_to_current_user() {
// Expected SID = current process user.
let expected_buffer = current_user_token_buffer().expect("get current user token");
let expected_sid = sid_from_token_buffer(&expected_buffer);
// Build the descriptor and a real server instance with a unique name.
let security = OwnedSecurityDescriptor::for_current_user().expect("build security descriptor");
let name = format!("\\\\.\\pipe\\ironrdp-agent-acl-test-{}", std::process::id());
let mut name_utf16: Vec<u16> = name.encode_utf16().collect();
name_utf16.push(0u16);
let _server = create_server_instance(&name, true, &security).expect("create pipe instance");
// Query the pipe's actual DACL.
let mut sd = PSECURITY_DESCRIPTOR(core::ptr::null_mut());
let mut dacl: *mut ACL = core::ptr::null_mut();
// SAFETY: `name_utf16` is a valid null-terminated pipe path; we request only the DACL; the
// out-pointers are valid. The returned SD is `LocalAlloc`'d and owned by us until freed below.
let result = unsafe {
GetNamedSecurityInfoW(
PCWSTR::from_raw(name_utf16.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(core::ptr::addr_of_mut!(dacl)),
None,
core::ptr::addr_of_mut!(sd),
)
};
assert_eq!(result, ERROR_SUCCESS, "GetNamedSecurityInfoW should succeed");
// `GetNamedSecurityInfoW` `LocalAlloc`'s the descriptor; reuse the production RAII guard so it
// is freed on drop at the end of the test even if an assertion below panics.
let _sd_guard = OwnedSecurityDescriptor(sd);
// The DACL must be protected (no inherited ACEs from the pipe namespace).
let mut control: u16 = 0;
let mut revision: u32 = 0;
// SAFETY: `sd` is a valid self-relative SD returned by `GetNamedSecurityInfoW`.
unsafe {
GetSecurityDescriptorControl(sd, core::ptr::addr_of_mut!(control), core::ptr::addr_of_mut!(revision))
}
.expect("get security descriptor control");
assert!(
(control & SE_DACL_PROTECTED.0) != 0,
"DACL must be protected so inherited ACEs cannot widen access"
);
// Exactly one ACE must be present.
let mut dacl_present = windows::core::BOOL::default();
let mut dacl_ptr: *mut ACL = core::ptr::null_mut();
let mut defaulted = windows::core::BOOL::default();
// SAFETY: `sd` is a valid SD; the out-pointers are valid.
unsafe {
GetSecurityDescriptorDacl(
sd,
core::ptr::addr_of_mut!(dacl_present),
core::ptr::addr_of_mut!(dacl_ptr),
core::ptr::addr_of_mut!(defaulted),
)
}
.expect("get dacl");
assert!(dacl_present.as_bool(), "DACL must be present");
assert!(!dacl_ptr.is_null(), "DACL pointer must not be null");
let mut size_info = ACL_SIZE_INFORMATION::default();
// SAFETY: `dacl_ptr` is a valid ACL; `size_info` is a valid out-buffer of the right size.
unsafe {
GetAclInformation(
dacl_ptr.cast_const(),
core::ptr::addr_of_mut!(size_info).cast::<core::ffi::c_void>(),
u32::try_from(size_of::<ACL_SIZE_INFORMATION>()).expect("acl size information fits in u32"),
AclSizeInformation,
)
}
.expect("get acl information");
assert_eq!(size_info.AceCount, 1, "DACL must contain exactly one ACE");
// The single ACE must be an allow-ACE granting GENERIC_ALL to the current user SID.
let mut ace_ptr: *mut core::ffi::c_void = core::ptr::null_mut();
// SAFETY: `dacl_ptr` is valid and holds one ACE (verified above); `ace_ptr` is a valid out-pointer.
unsafe { GetAce(dacl_ptr.cast_const(), 0, core::ptr::addr_of_mut!(ace_ptr)) }.expect("get ace");
assert!(!ace_ptr.is_null(), "ACE pointer must not be null");
// SAFETY: ACE 0 is an `ACCESS_ALLOWED_ACE` (SDDL "A;;" = allow) placed at DWORD alignment by
// the ACL; `read_unaligned` avoids any alignment assumption.
let ace: ACCESS_ALLOWED_ACE = unsafe { core::ptr::read_unaligned(ace_ptr.cast::<ACCESS_ALLOWED_ACE>()) };
assert_eq!(
ace.Header.AceType, 0u8, /* ACCESS_ALLOWED_ACE_TYPE */
"ACE must be an allow ACE"
);
// `GENERIC_ALL` (0x10000000) in the SDDL is mapped by the kernel to the file-object-specific
// `FILE_ALL_ACCESS` (0x001F01FF) when the descriptor is stored on a named pipe, so compare
// against the mapped value rather than the generic bit.
assert_eq!(
ace.Mask, 0x001F01FFu32, /* FILE_ALL_ACCESS */
"ACE must grant full access (GENERIC_ALL mapped to the pipe object)"
);
// The SID starts at `SidStart` and extends past the struct into the ACL buffer, so point into
// the in-place ACE rather than the local copy.
// SAFETY: `ace_ptr` is a non-null pointer to a valid `ACCESS_ALLOWED_ACE`; `SidStart` is the
// first DWORD of the variable-length SID that follows the fixed ACE header.
let ace_sid = PSID(unsafe { ace_ptr.byte_add(core::mem::offset_of!(ACCESS_ALLOWED_ACE, SidStart)) });
// SAFETY: both `ace_sid` and `expected_sid` are valid SIDs from the token / ACL.
let sids_equal = unsafe { EqualSid(ace_sid, expected_sid) }.is_ok();
assert!(sids_equal, "ACE SID must equal the current user SID");
}
}
}
pub use imp::{
Endpoint, Listener, connect, default_endpoint, default_endpoint_named, endpoint_from_string, prepare_endpoint,
};
#[cfg(unix)]
pub type ClientStream = tokio::net::UnixStream;
#[cfg(windows)]
pub type ClientStream = tokio::net::windows::named_pipe::NamedPipeClient;
@@ -1,4 +1,4 @@
//! Binary wire primitives shared by the IPC message codecs.
//! Binary wire primitives shared by the local RPC message codecs.
//!
//! Everything is little-endian and cursor-based so it composes directly with [`ironrdp_core`]'s
//! `Encode`/`Decode`/`DecodeOwned` traits. Strings (and string-shaped payloads) are length-delimited
@@ -1,4 +1,4 @@
//! Binary wire codec for [`PropertySet`].
//! Binary wire codec for [`PropertySet`] used by the local RPC protocol.
//!
//! This mirrors the shape of [`ironrdp_rdpfile::load`]/[`ironrdp_rdpfile::write`] but is binary and
//! cursor-based so it composes with [`ironrdp_core`]'s `Encode`/`DecodeOwned` traits.
@@ -113,6 +113,7 @@ fn request_variants_round_trip() {
last: true,
},
Request::NowDiagnostics,
Request::Shutdown,
];
for request in &requests {
+2 -1
View File
@@ -28,6 +28,7 @@ qoi = ["ironrdp/qoi"]
qoiz = ["ironrdp/qoiz"]
[dependencies]
ironrdp-agent = { path = "../ironrdp-agent", version = "0.1" }
ironrdp = { path = "../ironrdp", version = "0.17", features = ["connector", "cliprdr", "input", "pdu", "client", "client-all"] }
ironrdp-cfg = { path = "../ironrdp-cfg", version = "0.1" }
ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" }
@@ -38,7 +39,7 @@ winit = { version = "0.30", features = ["rwh_06"] }
softbuffer = "0.4"
# CLI
clap = { version = "4.6", features = ["derive", "cargo"] }
clap = { version = "4.6", features = ["derive", "cargo", "env"] }
inquire = "0.9"
proc-exit = "2"
+25 -2
View File
@@ -18,6 +18,28 @@ download and verification instructions.
ironrdp-viewer <HOSTNAME> --username <USERNAME> --password <PASSWORD>
```
You can provide the hostname and credentials through environment variables instead:
```shell
RDP_HOSTNAME=<HOSTNAME> RDP_USERNAME=<USERNAME> RDP_PASSWORD=<PASSWORD> ironrdp-viewer
```
## Agent RPC host
The viewer can host the same local RPC protocol used by `ironrdp-agent`, while keeping its visible
window:
```shell
ironrdp-viewer --rpc
ironrdp-agent --backend viewer connect --server <HOSTNAME> --username <USERNAME> --password <PASSWORD>
```
The agent automatically starts and reuses a viewer RPC host for normal operations. Its default
viewer endpoint is `ironrdp-viewer-<uid>.sock` on Unix or `\\.\pipe\ironrdp-viewer-<user>` on
Windows. Override it with `--endpoint` on the agent or `--rpc-endpoint` on the viewer, and stop the
selected host with `ironrdp-agent --backend viewer stop`. The GUI and RPC client share one RDP
session, including its framebuffer and input.
## `.rdp` file support
You can load a `.rdp` file with `--rdp-file <PATH>`.
@@ -50,8 +72,9 @@ Currently supported properties:
Property precedence is:
1. CLI options
2. `.rdp` file values
3. Defaults and interactive prompts
2. Environment variables
3. `.rdp` file values
4. Defaults and interactive prompts
Unknown or unsupported `.rdp` properties are ignored and do not cause parsing failures. Parse
issues are reported to stderr.
+112 -37
View File
@@ -7,6 +7,7 @@ use std::time::Instant;
use anyhow::Context as _;
use ironrdp::client::rdp::{RdpInputEvent, RdpInputSender, RdpOutputEvent};
use ironrdp_agent::daemon::Daemon;
use raw_window_handle::{DisplayHandle, HasDisplayHandle as _};
use smallvec::SmallVec;
use tracing::{debug, error, info, trace, warn};
@@ -19,8 +20,25 @@ use winit::window::{CursorIcon, CustomCursor, Window, WindowAttributes};
type WindowSurface = (Arc<Window>, softbuffer::Surface<DisplayHandle<'static>, Arc<Window>>);
/// Events delivered from the RDP engine and the viewer-hosted RPC server to the window.
pub enum ViewerEvent {
Output(RdpOutputEvent),
Frame {
buffer: Vec<u32>,
width: NonZeroU32,
height: NonZeroU32,
},
Shutdown,
}
/// Where local window input is sent.
pub enum InputTarget {
Direct(RdpInputSender),
Rpc(Arc<Daemon>),
}
pub struct App {
input_event_sender: RdpInputSender,
input_target: InputTarget,
context: softbuffer::Context<DisplayHandle<'static>>,
initial_window_size: PhysicalSize<u32>,
window: Option<WindowSurface>,
@@ -33,9 +51,21 @@ pub struct App {
impl App {
pub fn new(
event_loop: &EventLoop<RdpOutputEvent>,
event_loop: &EventLoop<ViewerEvent>,
input_event_sender: &RdpInputSender,
initial_window_size: PhysicalSize<u32>,
) -> anyhow::Result<Self> {
Self::new_with_input_target(
event_loop,
InputTarget::Direct(input_event_sender.clone()),
initial_window_size,
)
}
pub fn new_with_input_target(
event_loop: &EventLoop<ViewerEvent>,
input_target: InputTarget,
initial_window_size: PhysicalSize<u32>,
) -> anyhow::Result<Self> {
// SAFETY: We drop the softbuffer context right before the event loop is stopped, thus making this safe.
// FIXME: This is not a sufficient proof and the API is actually unsound as-is.
@@ -49,7 +79,7 @@ impl App {
let input_database = ironrdp::input::Database::new();
Ok(Self {
input_event_sender: input_event_sender.clone(),
input_target,
context,
initial_window_size,
window: None,
@@ -74,27 +104,51 @@ impl App {
let width = u16::try_from(size.width).expect("reasonable width");
let height = u16::try_from(size.height).expect("reasonable height");
match self.input_event_sender.try_send(RdpInputEvent::Resize {
width,
height,
scale_factor,
// TODO: it should be possible to get the physical size here, however winit doesn't make it straightforward.
// FreeRDP does it based on DPI reading grabbed via [`SDL_GetDisplayDPI`](https://wiki.libsdl.org/SDL2/SDL_GetDisplayDPI):
// https://github.com/FreeRDP/FreeRDP/blob/ba8cf8cf2158018fb7abbedb51ab245f369be813/client/SDL/sdl_monitor.cpp#L250-L262
// See also: https://github.com/rust-windowing/winit/issues/826
physical_size: None,
}) {
Ok(()) => self.last_size = None,
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
self.resize_timeout = Some(Instant::now() + Duration::from_millis(10));
}
Err(_) => {
self.last_size = None;
warn!("Unable to enqueue resize event because the RDP session is closed");
match &self.input_target {
InputTarget::Direct(input_event_sender) => match input_event_sender.try_send(RdpInputEvent::Resize {
width,
height,
scale_factor,
// TODO: it should be possible to get the physical size here, however winit doesn't make it straightforward.
// FreeRDP does it based on DPI reading grabbed via [`SDL_GetDisplayDPI`](https://wiki.libsdl.org/SDL2/SDL_GetDisplayDPI):
// https://github.com/FreeRDP/FreeRDP/blob/ba8cf8cf2158018fb7abbedb51ab245f369be813/client/SDL/sdl_monitor.cpp#L250-L262
// See also: https://github.com/rust-windowing/winit/issues/826
physical_size: None,
}) {
Ok(()) => self.last_size = None,
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
self.resize_timeout = Some(Instant::now() + Duration::from_millis(10));
}
Err(_) => {
self.last_size = None;
warn!("Unable to enqueue resize event because the RDP session is closed");
}
},
InputTarget::Rpc(daemon) => {
if daemon.resize(width, height).is_ok() {
self.last_size = None;
} else {
self.last_size = None;
warn!("Unable to resize the RPC-backed RDP session");
}
}
}
}
fn update_frame(&mut self, buffer: Vec<u32>, width: NonZeroU32, height: NonZeroU32) {
let Some((window, surface)) = self.window.as_mut() else {
return;
};
trace!(?width, ?height, "Received RPC-backed image");
self.buffer_size = (
u16::try_from(width.get()).expect("frame width fits in u16"),
u16::try_from(height.get()).expect("frame height fits in u16"),
);
self.buffer = buffer;
surface.resize(width, height).expect("surface resize");
window.request_redraw();
}
fn draw(&mut self) {
if self.buffer.is_empty() {
return;
@@ -108,7 +162,7 @@ impl App {
}
}
impl ApplicationHandler<RdpOutputEvent> for App {
impl ApplicationHandler<ViewerEvent> for App {
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
if let Some(timeout) = self.resize_timeout {
if let Some(timeout) = timeout.checked_duration_since(Instant::now()) {
@@ -157,9 +211,12 @@ impl ApplicationHandler<RdpOutputEvent> for App {
self.last_size = Some(size);
self.resize_timeout = Some(Instant::now() + Duration::from_secs(1));
}
WindowEvent::CloseRequested => {
self.input_event_sender.request_graceful_close();
}
WindowEvent::CloseRequested => match &self.input_target {
InputTarget::Direct(input_event_sender) => input_event_sender.request_graceful_close(),
InputTarget::Rpc(daemon) => {
let _ = daemon.disconnect();
}
},
WindowEvent::DroppedFile(_) => {
// TODO(#110): File upload
}
@@ -198,7 +255,7 @@ impl ApplicationHandler<RdpOutputEvent> for App {
};
apply_and_send_fast_path_events(
&self.input_event_sender,
&self.input_target,
&mut self.input_database,
core::iter::once(operation),
);
@@ -235,7 +292,7 @@ impl ApplicationHandler<RdpOutputEvent> for App {
add_operation(modifiers.state().alt_key(), ALT_LEFT);
add_operation(modifiers.state().super_key(), LOGO_LEFT);
apply_and_send_fast_path_events(&self.input_event_sender, &mut self.input_database, operations);
apply_and_send_fast_path_events(&self.input_target, &mut self.input_database, operations);
}
WindowEvent::CursorMoved { position, .. } => {
let win_size = window.inner_size();
@@ -246,7 +303,7 @@ impl ApplicationHandler<RdpOutputEvent> for App {
let operation = ironrdp::input::Operation::MouseMove(ironrdp::input::MousePosition { x, y });
apply_and_send_fast_path_events(
&self.input_event_sender,
&self.input_target,
&mut self.input_database,
core::iter::once(operation),
);
@@ -299,7 +356,7 @@ impl ApplicationHandler<RdpOutputEvent> for App {
}
};
apply_and_send_fast_path_events(&self.input_event_sender, &mut self.input_database, operations);
apply_and_send_fast_path_events(&self.input_target, &mut self.input_database, operations);
}
WindowEvent::MouseInput { state, button, .. } => {
let mouse_button = match button {
@@ -323,7 +380,7 @@ impl ApplicationHandler<RdpOutputEvent> for App {
};
apply_and_send_fast_path_events(
&self.input_event_sender,
&self.input_target,
&mut self.input_database,
core::iter::once(operation),
);
@@ -355,7 +412,16 @@ impl ApplicationHandler<RdpOutputEvent> for App {
}
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: RdpOutputEvent) {
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: ViewerEvent) {
let ViewerEvent::Output(event) = event else {
match event {
ViewerEvent::Frame { buffer, width, height } => self.update_frame(buffer, width, height),
ViewerEvent::Shutdown => event_loop.exit(),
ViewerEvent::Output(_) => unreachable!(),
}
return;
};
let Some((window, surface)) = self.window.as_mut() else {
return;
};
@@ -435,15 +501,24 @@ impl ApplicationHandler<RdpOutputEvent> for App {
}
fn apply_and_send_fast_path_events(
input_event_sender: &RdpInputSender,
input_target: &InputTarget,
input_database: &mut ironrdp::input::Database,
operations: impl IntoIterator<Item = ironrdp::input::Operation>,
) {
let Ok(permit) = input_event_sender.try_reserve() else {
return;
};
let input_events = input_database.apply(operations);
if !input_events.is_empty() {
permit.send(RdpInputEvent::FastPath(input_events));
match input_target {
InputTarget::Direct(input_event_sender) => {
let Ok(permit) = input_event_sender.try_reserve() else {
return;
};
let input_events = input_database.apply(operations);
if !input_events.is_empty() {
permit.send(RdpInputEvent::FastPath(input_events));
}
}
InputTarget::Rpc(daemon) => {
for operation in operations {
let _ = daemon.input(operation);
}
}
}
}
+36 -2
View File
@@ -62,6 +62,14 @@ struct Args {
#[clap(short, long, value_parser)]
log_file: Option<String>,
/// Run as a visible GUI host for the ironrdp-agent RPC protocol.
#[clap(long)]
rpc: bool,
/// Override the viewer RPC endpoint (defaults to the per-user viewer endpoint).
#[clap(long, requires = "rpc")]
rpc_endpoint: Option<String>,
#[clap(long, value_parser)]
gw_endpoint: Option<String>,
#[clap(long, value_parser)]
@@ -70,6 +78,7 @@ struct Args {
gw_pass: Option<String>,
/// An address on which the client will connect.
#[clap(env = "RDP_HOSTNAME")]
destination: Option<Destination>,
/// Path to a .rdp file to read the configuration from.
@@ -77,7 +86,7 @@ struct Args {
rdp_file: Option<PathBuf>,
/// A target RDP server user name
#[clap(short, long)]
#[clap(short, long, env = "RDP_USERNAME")]
username: Option<String>,
/// An optional target RDP server domain name
@@ -85,7 +94,7 @@ struct Args {
domain: Option<String>,
/// A target RDP server user password
#[clap(short, long)]
#[clap(short, long, env = "RDP_PASSWORD")]
password: Option<String>,
/// Proxy URL to connect to for the RDCleanPath
@@ -225,6 +234,8 @@ pub struct ViewerConfig {
// CLI-only settings that are not representable as `.rdp` file properties.
log_file: Option<String>,
dump_rdp: Option<PathBuf>,
rpc: bool,
rpc_endpoint: Option<String>,
}
impl ViewerConfig {
@@ -255,6 +266,19 @@ impl ViewerConfig {
let log_file = args.log_file.clone();
let dump_rdp = args.dump_rdp.clone();
if args.rpc {
if args.rdp_file.is_some() || dump_rdp.is_some() {
anyhow::bail!("--rpc cannot be combined with --rdp-file or --dump-rdp");
}
return Ok(Self {
builder: ConfigBuilder::new(),
log_file,
dump_rdp: None,
rpc: true,
rpc_endpoint: args.rpc_endpoint,
});
}
// The library overlays everything expressible as a `.rdp` property: destination, credentials,
// transport, channels, desktop size, audio, DVC proxies, etc.
let builder = ConfigBuilder::from_property_set(&properties)?;
@@ -270,6 +294,8 @@ impl ViewerConfig {
builder,
log_file,
dump_rdp,
rpc: false,
rpc_endpoint: None,
})
}
@@ -290,6 +316,14 @@ impl ViewerConfig {
pub fn dump_rdp(&self) -> Option<&std::path::Path> {
self.dump_rdp.as_deref()
}
pub fn rpc_mode(&self) -> bool {
self.rpc
}
pub fn rpc_endpoint(&self) -> Option<&str> {
self.rpc_endpoint.as_deref()
}
}
/// Apply CLI overrides on top of a builder that already reflects the `.rdp` file. Every flag that is
+82 -3
View File
@@ -1,8 +1,14 @@
#![allow(unused_crate_dependencies)] // false positives because there is both a library and a binary
use core::num::NonZeroU32;
use std::sync::Arc;
use anyhow::Context as _;
use ironrdp::client::rdp::{RdpClient, RdpOutputEvent};
use ironrdp_viewer::app::App;
use ironrdp_agent::daemon::Daemon;
use ironrdp_agent::transport;
use ironrdp_propertyset::PropertySet;
use ironrdp_viewer::app::{App, InputTarget, ViewerEvent};
use ironrdp_viewer::cli::ViewerConfig;
use tokio::runtime;
use tokio::sync::mpsc;
@@ -15,6 +21,10 @@ fn main() -> anyhow::Result<()> {
setup_logging(cli.log_file()).context("unable to initialize logging")?;
if cli.rpc_mode() {
return run_rpc(cli).context("RPC server");
}
let dump_rdp = cli.dump_rdp().map(ToOwned::to_owned);
let config = cli.into_config().context("configuration")?;
@@ -26,7 +36,7 @@ fn main() -> anyhow::Result<()> {
}
debug!("Initialize App");
let event_loop = EventLoop::<RdpOutputEvent>::with_user_event().build()?;
let event_loop = EventLoop::<ViewerEvent>::with_user_event().build()?;
let event_loop_proxy = event_loop.create_proxy();
let (output_event_sender, mut output_event_receiver) = mpsc::channel::<RdpOutputEvent>(64);
let initial_window_size = PhysicalSize::new(
@@ -51,7 +61,7 @@ fn main() -> anyhow::Result<()> {
// `tokio::sync::mpsc` channel. Bridging onto the GUI event loop is the binary's job.
rt.spawn(async move {
while let Some(event) = output_event_receiver.recv().await {
if event_loop_proxy.send_event(event).is_err() {
if event_loop_proxy.send_event(ViewerEvent::Output(event)).is_err() {
// The event loop is gone; nothing left to forward.
break;
}
@@ -69,6 +79,75 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
fn run_rpc(cli: ViewerConfig) -> anyhow::Result<()> {
let endpoint = cli
.rpc_endpoint()
.map(|value| transport::endpoint_from_string(value.to_owned()))
.unwrap_or_else(|| transport::default_endpoint_named("ironrdp-viewer"));
debug!(%endpoint, "Initialize viewer RPC server");
let event_loop = EventLoop::<ViewerEvent>::with_user_event().build()?;
let event_loop_proxy = event_loop.create_proxy();
let (notification_sender, mut notification_receiver) = mpsc::unbounded_channel();
let daemon = Arc::new(Daemon::with_overlay(PropertySet::new()).with_notification(notification_sender));
let runtime = runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("unable to create tokio runtime")?;
let frame_daemon = Arc::clone(&daemon);
let frame_proxy = event_loop_proxy.clone();
runtime.spawn(async move {
while notification_receiver.recv().await.is_some() {
let Some(frame) = frame_daemon.current_frame() else {
continue;
};
let (Some(width), Some(height)) = (
NonZeroU32::new(u32::from(frame.width)),
NonZeroU32::new(u32::from(frame.height)),
) else {
continue;
};
if frame_proxy
.send_event(ViewerEvent::Frame {
buffer: frame.pixels,
width,
height,
})
.is_err()
{
break;
}
}
});
let server_daemon = Arc::clone(&daemon);
let server_proxy = event_loop_proxy;
std::thread::Builder::new()
.name("ironrdp-viewer-rpc".to_owned())
.spawn(move || {
let server_runtime = runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("unable to create viewer RPC runtime");
server_runtime.block_on(async move {
if let Err(error) = ironrdp_agent::daemon::serve(endpoint, server_daemon).await {
tracing::error!(error = format!("{error:#}"), "Viewer RPC server stopped with an error");
}
let _ = server_proxy.send_event(ViewerEvent::Shutdown);
});
})
.context("unable to spawn viewer RPC server")?;
let mut app = App::new_with_input_target(&event_loop, InputTarget::Rpc(daemon), PhysicalSize::new(1024, 768))
.context("unable to initialize App")?;
debug!("Run viewer RPC App");
event_loop.run_app(&mut app)?;
Ok(())
}
fn setup_logging(log_file: Option<&str>) -> anyhow::Result<()> {
use std::fs::OpenOptions;