bssh 2.0.1

Parallel SSH command execution tool for cluster management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH server implementation using russh.
//!
//! This module provides the core SSH server functionality for bssh-server,
//! including connection handling, authentication, and session management.
//!
//! # Overview
//!
//! The server module consists of:
//!
//! - [`BsshServer`]: Main server struct that accepts connections
//! - [`SshHandler`]: Handles SSH protocol events for each connection
//! - [`SessionManager`]: Tracks active sessions
//! - [`ServerConfig`]: Server configuration options
//! - [`auth`]: Authentication providers (public key, password)
//!
//! # Example
//!
//! ```no_run
//! use bssh::server::{BsshServer, ServerConfig};
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let config = ServerConfig::builder()
//!         .host_key("/path/to/ssh_host_ed25519_key")
//!         .listen_address("0.0.0.0:2222")
//!         .build();
//!
//!     let server = BsshServer::new(config);
//!     server.run().await
//! }
//! ```

pub mod audit;
pub mod auth;
pub mod config;
pub mod exec;
pub mod filter;
pub mod handler;
pub mod pty;
pub mod scp;
pub mod security;
pub mod session;
pub mod sftp;
pub mod shell;

use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use russh::server::Server;
use tokio::net::{TcpListener, ToSocketAddrs};
use tokio::sync::RwLock;

use crate::shared::rate_limit::RateLimiter;

pub use self::config::{ServerConfig, ServerConfigBuilder};
pub use self::exec::{CommandExecutor, ExecConfig};
pub use self::handler::SshHandler;
pub use self::pty::{PtyConfig as PtyMasterConfig, PtyMaster};
pub use self::security::{
    AccessPolicy, AuthRateLimitConfig, AuthRateLimiter, IpAccessControl, SharedIpAccessControl,
};
pub use self::session::{
    ChannelMode, ChannelState, PtyConfig, SessionConfig, SessionError, SessionId, SessionInfo,
    SessionManager, SessionStats,
};
pub use self::shell::ShellSession;

/// The main SSH server struct.
///
/// `BsshServer` manages the SSH server lifecycle, including accepting
/// connections and creating handlers for each client.
pub struct BsshServer {
    /// Server configuration.
    config: Arc<ServerConfig>,

    /// Shared session manager for tracking active connections.
    sessions: Arc<RwLock<SessionManager>>,
}

impl BsshServer {
    /// Create a new SSH server with the given configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Server configuration
    ///
    /// # Example
    ///
    /// ```
    /// use bssh::server::{BsshServer, ServerConfig};
    ///
    /// let config = ServerConfig::builder()
    ///     .host_key("/etc/ssh/ssh_host_ed25519_key")
    ///     .build();
    /// let server = BsshServer::new(config);
    /// ```
    pub fn new(config: ServerConfig) -> Self {
        let session_config = config.session_config();
        let sessions = SessionManager::with_config(session_config);
        Self {
            config: Arc::new(config),
            sessions: Arc::new(RwLock::new(sessions)),
        }
    }

    /// Get the server configuration.
    pub fn config(&self) -> &ServerConfig {
        &self.config
    }

    /// Get the session manager.
    pub fn sessions(&self) -> &Arc<RwLock<SessionManager>> {
        &self.sessions
    }

    /// Run the SSH server, listening on the configured address.
    ///
    /// This method starts the server and blocks until it is shut down.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No host keys are configured
    /// - Host keys cannot be loaded
    /// - The server fails to bind to the configured address
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bssh::server::{BsshServer, ServerConfig};
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let config = ServerConfig::builder()
    ///         .host_key("/etc/ssh/ssh_host_ed25519_key")
    ///         .listen_address("0.0.0.0:2222")
    ///         .build();
    ///
    ///     let server = BsshServer::new(config);
    ///     server.run().await
    /// }
    /// ```
    pub async fn run(&self) -> Result<()> {
        let addr = &self.config.listen_address;
        tracing::info!(address = %addr, "Starting SSH server");

        let russh_config = self.build_russh_config()?;
        self.run_on_address(Arc::new(russh_config), addr).await
    }

    /// Run the SSH server on a specific address.
    ///
    /// This allows running on a different address than the one in the config.
    ///
    /// # Arguments
    ///
    /// * `addr` - The address to listen on
    pub async fn run_at(&self, addr: impl ToSocketAddrs + std::fmt::Debug) -> Result<()> {
        tracing::info!(address = ?addr, "Starting SSH server");

        let russh_config = self.build_russh_config()?;
        self.run_on_address(Arc::new(russh_config), addr).await
    }

    /// Build the russh server configuration from our config.
    fn build_russh_config(&self) -> Result<russh::server::Config> {
        if !self.config.has_host_keys() {
            anyhow::bail!("No host keys configured. At least one host key is required.");
        }

        let mut keys = Vec::new();
        for key_path in &self.config.host_keys {
            let key = load_host_key(key_path)?;
            keys.push(key);
        }

        tracing::info!(key_count = keys.len(), "Loaded host keys");

        Ok(russh::server::Config {
            keys,
            auth_rejection_time: Duration::from_secs(3),
            auth_rejection_time_initial: Some(Duration::from_secs(0)),
            max_auth_attempts: self.config.max_auth_attempts as usize,
            inactivity_timeout: self.config.idle_timeout(),
            ..Default::default()
        })
    }

    /// Internal method to run the server on an address.
    async fn run_on_address(
        &self,
        russh_config: Arc<russh::server::Config>,
        addr: impl ToSocketAddrs,
    ) -> Result<()> {
        let socket = TcpListener::bind(addr)
            .await
            .context("Failed to bind to address")?;

        tracing::info!(
            local_addr = ?socket.local_addr(),
            "SSH server listening"
        );

        // Create shared rate limiter for all handlers
        // Allow burst of 100 auth attempts, refill 10 attempts per second
        // This allows rapid testing while still providing protection against brute force
        let rate_limiter = RateLimiter::with_simple_config(100, 10.0);

        // Create auth rate limiter with configuration
        // Parse whitelist IPs from config
        let whitelist_ips: Vec<std::net::IpAddr> = self
            .config
            .whitelist_ips
            .iter()
            .filter_map(|s| {
                s.parse().map_err(|e| {
                    tracing::warn!(ip = %s, error = %e, "Invalid whitelist IP address in config, skipping");
                    e
                }).ok()
            })
            .collect();

        let auth_config = AuthRateLimitConfig::new(
            self.config.max_auth_attempts,
            self.config.auth_window_secs,
            self.config.ban_time_secs,
        )
        .with_whitelist(whitelist_ips);

        let auth_rate_limiter = AuthRateLimiter::new(auth_config);

        tracing::info!(
            max_attempts = self.config.max_auth_attempts,
            auth_window_secs = self.config.auth_window_secs,
            ban_time_secs = self.config.ban_time_secs,
            whitelist_count = self.config.whitelist_ips.len(),
            "Auth rate limiter configured"
        );

        // Create IP access control from configuration
        let ip_access_control =
            IpAccessControl::from_config(&self.config.allowed_ips, &self.config.blocked_ips)
                .context("Failed to configure IP access control")?;

        let shared_ip_access = SharedIpAccessControl::new(ip_access_control);

        // Start background cleanup task for auth rate limiter
        let cleanup_limiter = auth_rate_limiter.clone();
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(60));
            loop {
                interval.tick().await;
                cleanup_limiter.cleanup().await;
            }
        });

        let mut server = BsshServerRunner {
            config: Arc::clone(&self.config),
            sessions: Arc::clone(&self.sessions),
            rate_limiter,
            auth_rate_limiter,
            ip_access_control: shared_ip_access,
        };

        // Use run_on_socket which handles the server loop
        server
            .run_on_socket(russh_config, &socket)
            .await
            .map_err(|e| anyhow::anyhow!("Server error: {}", e))
    }

    /// Get the number of active sessions.
    pub async fn session_count(&self) -> usize {
        self.sessions.read().await.session_count()
    }

    /// Check if the server is at connection capacity.
    pub async fn is_at_capacity(&self) -> bool {
        self.sessions.read().await.is_at_capacity()
    }
}

/// Internal struct that implements the russh::server::Server trait.
///
/// This is separate from BsshServer to allow BsshServer to be !Clone
/// while still implementing the Server trait which requires Clone.
#[derive(Clone)]
struct BsshServerRunner {
    config: Arc<ServerConfig>,
    sessions: Arc<RwLock<SessionManager>>,
    /// Shared rate limiter for authentication attempts across all handlers
    rate_limiter: RateLimiter<String>,
    /// Auth rate limiter with ban support (fail2ban-like)
    auth_rate_limiter: AuthRateLimiter,
    /// IP-based access control
    ip_access_control: SharedIpAccessControl,
}

impl russh::server::Server for BsshServerRunner {
    type Handler = SshHandler;

    fn new_client(&mut self, peer_addr: Option<SocketAddr>) -> Self::Handler {
        // Check IP access control before creating handler
        if let Some(addr) = peer_addr {
            let ip = addr.ip();

            // Check IP access control (synchronous to avoid blocking)
            if self.ip_access_control.check_sync(&ip) == AccessPolicy::Deny {
                tracing::info!(
                    ip = %ip,
                    "Connection rejected by IP access control"
                );
                // Return a handler that will immediately reject
                // We can't return None here due to trait constraints,
                // so we'll mark it for rejection in the handler
                return SshHandler::rejected(
                    peer_addr,
                    Arc::clone(&self.config),
                    Arc::clone(&self.sessions),
                );
            }

            // Check if banned by auth rate limiter
            // Use try_read to avoid blocking in sync context
            if let Ok(is_banned) = tokio::runtime::Handle::try_current()
                .map(|h| h.block_on(self.auth_rate_limiter.is_banned(&ip)))
            {
                if is_banned {
                    tracing::info!(
                        ip = %ip,
                        "Connection rejected from banned IP"
                    );
                    return SshHandler::rejected(
                        peer_addr,
                        Arc::clone(&self.config),
                        Arc::clone(&self.sessions),
                    );
                }
            }
        }

        tracing::info!(
            peer = ?peer_addr,
            "New client connection"
        );

        SshHandler::with_rate_limiters(
            peer_addr,
            Arc::clone(&self.config),
            Arc::clone(&self.sessions),
            self.rate_limiter.clone(),
            self.auth_rate_limiter.clone(),
        )
    }

    fn handle_session_error(&mut self, error: <Self::Handler as russh::server::Handler>::Error) {
        tracing::error!(
            error = %error,
            "Session error"
        );
    }
}

/// Load an SSH host key from a file.
///
/// # Arguments
///
/// * `path` - Path to the private key file
///
/// # Errors
///
/// Returns an error if the key file cannot be read or parsed.
fn load_host_key(path: impl AsRef<Path>) -> Result<russh::keys::PrivateKey> {
    let path = path.as_ref();
    tracing::debug!(path = %path.display(), "Loading host key");

    russh::keys::PrivateKey::read_openssh_file(path)
        .with_context(|| format!("Failed to load host key from {}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_server_creation() {
        let config = ServerConfig::builder()
            .listen_address("127.0.0.1:2222")
            .max_connections(50)
            .build();

        let server = BsshServer::new(config);

        assert_eq!(server.config().listen_address, "127.0.0.1:2222");
        assert_eq!(server.config().max_connections, 50);
    }

    #[test]
    fn test_build_russh_config_no_keys() {
        let config = ServerConfig::builder().build();
        let server = BsshServer::new(config);

        let result = server.build_russh_config();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No host keys"));
    }

    #[tokio::test]
    async fn test_session_count() {
        let config = ServerConfig::builder().host_key("/nonexistent/key").build();
        let server = BsshServer::new(config);

        assert_eq!(server.session_count().await, 0);
        assert!(!server.is_at_capacity().await);
    }

    #[tokio::test]
    async fn test_session_manager_access() {
        let config = ServerConfig::builder()
            .max_connections(10)
            .host_key("/nonexistent/key")
            .build();
        let server = BsshServer::new(config);

        {
            let mut sessions = server.sessions().write().await;
            let info = sessions.create_session(None);
            assert!(info.is_some());
        }

        assert_eq!(server.session_count().await, 1);
    }
}