Lines
89.71 %
Functions
100 %
Branches
//! Accept loop with a cap on unauthenticated connections and a deadline to
//! authenticate, in the manner of OpenSSH `MaxStartups`.
//!
//! russh offers neither, so the loop is built on its public `run_stream`.
//! A connection over the cap is dropped before the SSH banner. A connection
//! that has not authenticated when the deadline passes has its socket shut
//! down, which ends it even while it stalls in key exchange, where russh
//! reads no disconnect request. The cap counts a connection until it
//! authenticates, closes or times out.
use crate::handler::{Session_, SshdState, log_session_error};
use russh::server::{Config, Server, run_stream};
use std::net::Shutdown;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::watch;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::time::{Instant, sleep, timeout_at};
/// Pause after a failed accept (descriptor exhaustion, say), so it cannot spin.
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
#[derive(Debug, Clone, Copy)]
pub struct AcceptLimits {
pub max_startups: usize,
pub pre_auth: Duration,
}
/// Accepts connections for the life of the daemon; a failed accept is logged and retried.
pub async fn serve(
state: &mut SshdState,
config: Arc<Config>,
listener: &TcpListener,
limits: AcceptLimits,
) {
let startups = Arc::new(Semaphore::new(limits.max_startups));
loop {
let (socket, peer) = match listener.accept().await {
Ok(accepted) => accepted,
Err(err) => {
tracing::warn!("accept failed: {err}");
sleep(ACCEPT_RETRY).await;
continue;
};
let Ok(permit) = Arc::clone(&startups).try_acquire_owned() else {
tracing::debug!(
"connection from {peer} refused: {} unauthenticated already",
limits.max_startups
);
let handler = state.new_client(Some(peer));
let deadline = Instant::now() + limits.pre_auth;
tokio::spawn(connection(
Arc::clone(&config),
socket,
handler,
deadline,
permit,
));
async fn connection(
socket: TcpStream,
handler: Session_,
deadline: Instant,
permit: OwnedSemaphorePermit,
let (socket, killer) = match split_killer(socket) {
Ok(pair) => pair,
Err(err) => return tracing::warn!("socket setup failed: {err}"),
tokio::spawn(enforce_deadline(
handler.authenticated(),
killer,
let served = async { run_stream(config, socket, handler).await?.await }.await;
if let Err(err) = served {
log_session_error(&err);
/// The socket for russh, and a second handle on it that can shut it down from outside.
fn split_killer(socket: TcpStream) -> std::io::Result<(TcpStream, std::net::TcpStream)> {
let std_socket = socket.into_std()?;
let killer = std_socket.try_clone()?;
Ok((TcpStream::from_std(std_socket)?, killer))
/// Frees the startup slot at login, at close (the handler drops the sender) or at the
/// deadline, and in the last case also cuts the connection.
async fn enforce_deadline(
mut authenticated: watch::Receiver<bool>,
killer: std::net::TcpStream,
let timed_out = timeout_at(deadline, authenticated.wait_for(|done| *done))
.await
.is_err();
drop(permit);
if timed_out {
tracing::info!("not authenticated before the deadline; closing");
if let Err(err) = killer.shutdown(Shutdown::Both) {
tracing::debug!("deadline shutdown failed: {err}");