Skip to content

Commit 23a9784

Browse files
fix(agent): harden package broker pipe against connection floods (#1902)
1 parent 1fe893d commit 23a9784

2 files changed

Lines changed: 88 additions & 44 deletions

File tree

‎devolutions-agent/src/broker/auth.rs‎

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -20,50 +20,40 @@ use crate::code_signing::validate_devolutions_authenticode_signature;
2020
pub(crate) struct PipeClient {
2121
process_id: u32,
2222
executable_path: PathBuf,
23-
user: ClientUser,
24-
}
25-
26-
#[derive(Clone, Debug)]
27-
struct ClientUser {
2823
/// Security identifier of the pipe client process token user, captured at connect.
29-
sid: Sid,
30-
domain: String,
31-
name: String,
24+
user_sid: Sid,
3225
}
3326

3427
impl PipeClient {
28+
/// Captures the identity of the process on the other end of a connected pipe instance.
29+
///
30+
/// Deliberately limited to fast, local syscalls (no account-name resolution, which may
31+
/// hit a domain controller), because it runs before any signature gate and is therefore
32+
/// unauthenticated work a connection flood can trigger.
3533
pub(crate) fn from_connected_pipe(server: &NamedPipeServer) -> anyhow::Result<Self> {
3634
let process_id = connected_pipe_client_process_id(server).context("failed to query pipe client process id")?;
3735
let process = Process::get_by_pid(process_id, PROCESS_QUERY_LIMITED_INFORMATION)
3836
.with_context(|| format!("failed to open pipe client process {process_id}"))?;
3937
let executable_path = process
4038
.exe_path()
4139
.with_context(|| format!("failed to query pipe client process {process_id} executable path"))?;
42-
let sid = process
40+
let user_sid = process
4341
.token(TOKEN_QUERY)
4442
.with_context(|| format!("failed to open pipe client process {process_id} token"))?
4543
.sid_and_attributes()
4644
.with_context(|| format!("failed to query pipe client process {process_id} token user"))?
4745
.sid;
48-
let account = sid
49-
.lookup_account(None)
50-
.with_context(|| format!("failed to resolve pipe client process {process_id} user"))?;
51-
let user = ClientUser {
52-
sid,
53-
domain: account.domain_name.to_string_lossy(),
54-
name: account.name.to_string_lossy(),
55-
};
5646

5747
Ok(Self {
5848
process_id,
5949
executable_path,
60-
user,
50+
user_sid,
6151
})
6252
}
6353

6454
/// Security identifier of the authenticated pipe client user, captured at connect.
6555
pub(crate) fn user_sid(&self) -> &Sid {
66-
&self.user.sid
56+
&self.user_sid
6757
}
6858

6959
pub(crate) fn validate_request(
@@ -116,15 +106,28 @@ impl PipeClient {
116106
let requested_sid = resolve_account_sid(effective_user)
117107
.with_context(|| format!("failed to resolve request effective_user '{effective_user}'"))?;
118108

119-
if requested_sid == self.user.sid {
109+
if requested_sid == self.user_sid {
120110
return Ok(());
121111
}
122112

113+
// Resolve the client account name lazily, only on this rare error path; doing it at
114+
// connect time would be unauthenticated work triggerable by a connection flood.
115+
let client_account = self
116+
.user_sid
117+
.lookup_account(None)
118+
.map(|account| {
119+
format!(
120+
"{}\\{}",
121+
account.domain_name.to_string_lossy(),
122+
account.name.to_string_lossy()
123+
)
124+
})
125+
.unwrap_or_else(|_| String::from("<unresolved>"));
126+
123127
bail!(
124-
"pipe client user '{}\\{}' ({}) does not match request effective_user '{}' ({})",
125-
self.user.domain,
126-
self.user.name,
127-
self.user.sid,
128+
"pipe client user '{}' ({}) does not match request effective_user '{}' ({})",
129+
client_account,
130+
self.user_sid,
128131
effective_user,
129132
requested_sid
130133
)
@@ -256,21 +259,16 @@ mod tests {
256259
}
257260

258261
fn system_client() -> PipeClient {
259-
let (domain, name) = system_account_names();
260262
PipeClient {
261263
process_id: 0,
262264
executable_path: PathBuf::new(),
263-
user: ClientUser {
264-
sid: system_sid(),
265-
domain,
266-
name,
267-
},
265+
user_sid: system_sid(),
268266
}
269267
}
270268

271269
#[cfg(not(feature = "dev-skip-broker-signature"))]
272-
fn client_user() -> ClientUser {
273-
system_client().user
270+
fn client_user_sid() -> Sid {
271+
system_client().user_sid
274272
}
275273

276274
#[test]
@@ -355,7 +353,7 @@ mod tests {
355353
let client = PipeClient {
356354
process_id: std::process::id(),
357355
executable_path: std::env::current_exe().expect("current test executable path"),
358-
user: client_user(),
356+
user_sid: client_user_sid(),
359357
};
360358

361359
assert!(client.validate_signature(true).is_err());

‎devolutions-agent/src/broker/pipe.rs‎

Lines changed: 57 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ mod windows_pipe {
99

1010
use anyhow::Context as _;
1111
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
12+
use tokio::sync::Semaphore;
1213
use tokio_util::sync::CancellationToken;
1314
use tracing::{error, info, warn};
1415
use win_api_wrappers::identity::sid::Sid;
@@ -25,13 +26,44 @@ mod windows_pipe {
2526
/// Default pipe name for the package broker.
2627
pub const DEFAULT_PIPE_NAME: &str = r"\\.\pipe\Devolutions.Now.PackageBroker.v1";
2728

29+
/// Maximum number of concurrently served pipe connections.
30+
///
31+
/// Connection setup performs unauthenticated work (client process identity lookups)
32+
/// before any signature gate, so a connection flood could otherwise trigger unbounded
33+
/// work and task spawning. While all slots are taken, no pipe instance is listening and
34+
/// further clients fail to connect until a slot frees up.
35+
const MAX_CONCURRENT_CONNECTIONS: usize = 16;
36+
37+
/// Deadline for serving a single pipe connection, from accept to response completion.
38+
///
39+
/// Each connection serves exactly one HTTP request (`keep_alive` is disabled) and all
40+
/// endpoints respond without blocking on package operations (execution is asynchronous,
41+
/// tracked via the operation tracker), so a healthy exchange completes well within this
42+
/// deadline. Without it, idle clients holding their connection open without sending a
43+
/// request would each pin a connection slot indefinitely and could exhaust the pool.
44+
const CONNECTION_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
45+
2846
/// Start the named pipe server and accept connections until shutdown.
2947
pub async fn run_pipe_server(state: Arc<BrokerState>, shutdown: CancellationToken) -> anyhow::Result<()> {
3048
let pipe_name = state.pipe_name.clone();
3149
info!(%pipe_name, "Starting named pipe server");
3250

51+
let connection_permits = Arc::new(Semaphore::new(MAX_CONCURRENT_CONNECTIONS));
52+
3353
let mut first_instance = true;
3454
loop {
55+
// Wait for a free connection slot before exposing a new pipe instance,
56+
// bounding the number of concurrently served connections.
57+
let permit = tokio::select! {
58+
permit = Arc::clone(&connection_permits).acquire_owned() => {
59+
permit.expect("the semaphore is never closed")
60+
}
61+
_ = shutdown.cancelled() => {
62+
info!("Pipe server shutting down");
63+
return Ok(());
64+
}
65+
};
66+
3567
// Create a new pipe instance for each connection.
3668
let server = create_pipe_instance(&pipe_name, first_instance)?;
3769
first_instance = false;
@@ -40,18 +72,32 @@ mod windows_pipe {
4072
result = server.connect() => {
4173
match result {
4274
Ok(()) => {
43-
let client = match PipeClient::from_connected_pipe(&server) {
44-
Ok(client) => client,
45-
Err(error) => {
46-
warn!(%error, "Rejected named pipe client");
47-
continue;
48-
}
49-
};
50-
info!("Client connected to named pipe");
51-
let router = build_router_for_client(Arc::clone(&state), client);
75+
let state = Arc::clone(&state);
5276
tokio::spawn(async move {
53-
serve_connection(server, router).await;
54-
info!("Client disconnected from named pipe");
77+
// The permit is held for the lifetime of the connection task.
78+
let _permit = permit;
79+
80+
let serve = async move {
81+
// Capture the client identity off the accept loop so a slow
82+
// lookup cannot stall accepting other connections.
83+
let client = match PipeClient::from_connected_pipe(&server) {
84+
Ok(client) => client,
85+
Err(error) => {
86+
warn!(%error, "Rejected named pipe client");
87+
return;
88+
}
89+
};
90+
info!("Client connected to named pipe");
91+
let router = build_router_for_client(state, client);
92+
serve_connection(server, router).await;
93+
info!("Client disconnected from named pipe");
94+
};
95+
96+
// Enforce a deadline so idle or slow clients cannot pin
97+
// a connection slot indefinitely.
98+
if tokio::time::timeout(CONNECTION_DEADLINE, serve).await.is_err() {
99+
warn!("Closed named pipe connection: deadline exceeded");
100+
}
55101
});
56102
}
57103
Err(error) => {

0 commit comments

Comments
 (0)