1
//! Accept loop with a cap on unauthenticated connections and a deadline to
2
//! authenticate, in the manner of OpenSSH `MaxStartups`.
3
//!
4
//! russh offers neither, so the loop is built on its public `run_stream`.
5
//! A connection over the cap is dropped before the SSH banner. A connection
6
//! that has not authenticated when the deadline passes has its socket shut
7
//! down, which ends it even while it stalls in key exchange, where russh
8
//! reads no disconnect request. The cap counts a connection until it
9
//! authenticates, closes or times out.
10

            
11
use crate::handler::{Session_, SshdState, log_session_error};
12
use russh::server::{Config, Server, run_stream};
13
use std::net::Shutdown;
14
use std::sync::Arc;
15
use std::time::Duration;
16
use tokio::net::{TcpListener, TcpStream};
17
use tokio::sync::watch;
18
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
19
use tokio::time::{Instant, sleep, timeout_at};
20

            
21
/// Pause after a failed accept (descriptor exhaustion, say), so it cannot spin.
22
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
23

            
24
#[derive(Debug, Clone, Copy)]
25
pub struct AcceptLimits {
26
    pub max_startups: usize,
27
    pub pre_auth: Duration,
28
}
29

            
30
/// Accepts connections for the life of the daemon; a failed accept is logged and retried.
31
28
pub async fn serve(
32
28
    state: &mut SshdState,
33
28
    config: Arc<Config>,
34
28
    listener: &TcpListener,
35
28
    limits: AcceptLimits,
36
28
) {
37
28
    let startups = Arc::new(Semaphore::new(limits.max_startups));
38
    loop {
39
59
        let (socket, peer) = match listener.accept().await {
40
31
            Ok(accepted) => accepted,
41
            Err(err) => {
42
                tracing::warn!("accept failed: {err}");
43
                sleep(ACCEPT_RETRY).await;
44
                continue;
45
            }
46
        };
47
31
        let Ok(permit) = Arc::clone(&startups).try_acquire_owned() else {
48
1
            tracing::debug!(
49
                "connection from {peer} refused: {} unauthenticated already",
50
                limits.max_startups
51
            );
52
1
            continue;
53
        };
54
30
        let handler = state.new_client(Some(peer));
55
30
        let deadline = Instant::now() + limits.pre_auth;
56
30
        tokio::spawn(connection(
57
30
            Arc::clone(&config),
58
30
            socket,
59
30
            handler,
60
30
            deadline,
61
30
            permit,
62
30
        ));
63
    }
64
}
65

            
66
30
async fn connection(
67
30
    config: Arc<Config>,
68
30
    socket: TcpStream,
69
30
    handler: Session_,
70
30
    deadline: Instant,
71
30
    permit: OwnedSemaphorePermit,
72
30
) {
73
30
    let (socket, killer) = match split_killer(socket) {
74
30
        Ok(pair) => pair,
75
        Err(err) => return tracing::warn!("socket setup failed: {err}"),
76
    };
77
30
    tokio::spawn(enforce_deadline(
78
30
        handler.authenticated(),
79
30
        killer,
80
30
        deadline,
81
30
        permit,
82
30
    ));
83
30
    let served = async { run_stream(config, socket, handler).await?.await }.await;
84
28
    if let Err(err) = served {
85
15
        log_session_error(&err);
86
13
    }
87
28
}
88

            
89
/// The socket for russh, and a second handle on it that can shut it down from outside.
90
30
fn split_killer(socket: TcpStream) -> std::io::Result<(TcpStream, std::net::TcpStream)> {
91
30
    let std_socket = socket.into_std()?;
92
30
    let killer = std_socket.try_clone()?;
93
30
    Ok((TcpStream::from_std(std_socket)?, killer))
94
30
}
95

            
96
/// Frees the startup slot at login, at close (the handler drops the sender) or at the
97
/// deadline, and in the last case also cuts the connection.
98
30
async fn enforce_deadline(
99
30
    mut authenticated: watch::Receiver<bool>,
100
30
    killer: std::net::TcpStream,
101
30
    deadline: Instant,
102
30
    permit: OwnedSemaphorePermit,
103
30
) {
104
53
    let timed_out = timeout_at(deadline, authenticated.wait_for(|done| *done))
105
30
        .await
106
        .is_err();
107
28
    drop(permit);
108
28
    if timed_out {
109
4
        tracing::info!("not authenticated before the deadline; closing");
110
4
        if let Err(err) = killer.shutdown(Shutdown::Both) {
111
            tracing::debug!("deadline shutdown failed: {err}");
112
4
        }
113
24
    }
114
28
}