bssh 2.1.2

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
// 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.

use super::core::SshClient;
use crate::jump::{JumpHostChain, parse_jump_hosts};
use crate::ssh::known_hosts::StrictHostKeyChecking;
use crate::ssh::tokio_client::{AuthMethod, Client, SshConnectionConfig};
use anyhow::{Context, Result};
use std::path::Path;
use std::time::Duration;

// SSH connection timeout design:
// - 30 seconds accommodates slow networks and SSH negotiation
// - Industry standard for SSH client connections
// - Balances user patience with reliability on poor networks
const SSH_CONNECT_TIMEOUT_SECS: u64 = 30;

impl SshClient {
    /// Determine the authentication method based on provided parameters
    pub(super) async fn determine_auth_method(
        &self,
        key_path: Option<&Path>,
        use_agent: bool,
        use_password: bool,
        #[cfg(target_os = "macos")] use_keychain: bool,
    ) -> Result<AuthMethod> {
        // Use centralized authentication logic from auth module
        let mut auth_ctx =
            crate::ssh::auth::AuthContext::new(self.username.clone(), self.host.clone())
                .with_context(|| {
                    format!("Invalid credentials for {}@{}", self.username, self.host)
                })?;

        // Set key path if provided
        if let Some(path) = key_path {
            auth_ctx = auth_ctx
                .with_key_path(Some(path.to_path_buf()))
                .with_context(|| format!("Invalid SSH key path: {path:?}"))?;
        }

        auth_ctx = auth_ctx.with_agent(use_agent).with_password(use_password);

        #[cfg(target_os = "macos")]
        {
            auth_ctx = auth_ctx.with_keychain(use_keychain);
        }

        auth_ctx.determine_method().await
    }

    /// Create a direct SSH connection (no jump hosts)
    pub(super) async fn connect_direct(
        &self,
        auth_method: &AuthMethod,
        strict_mode: StrictHostKeyChecking,
        connect_timeout_seconds: Option<u64>,
        ssh_connection_config: Option<&SshConnectionConfig>,
    ) -> Result<Client> {
        // SECURITY: Add rate limiting before connection attempts
        const RATE_LIMIT_DELAY: Duration = Duration::from_millis(100);
        tokio::time::sleep(RATE_LIMIT_DELAY).await;

        // SECURITY: Capture start time for timing attack mitigation
        let start_time = std::time::Instant::now();

        let addr = (self.host.as_str(), self.port);
        let check_method = crate::ssh::known_hosts::get_check_method(strict_mode);

        let connect_timeout =
            Duration::from_secs(connect_timeout_seconds.unwrap_or(SSH_CONNECT_TIMEOUT_SECS));

        let default_conn_cfg;
        let conn_cfg = match ssh_connection_config {
            Some(c) => c,
            None => {
                default_conn_cfg = SshConnectionConfig::default();
                &default_conn_cfg
            }
        };

        let result = match tokio::time::timeout(
            connect_timeout,
            Client::connect_with_ssh_config(
                addr,
                &self.username,
                auth_method.clone(),
                check_method,
                conn_cfg,
            ),
        )
        .await
        {
            Ok(Ok(client)) => Ok(client),
            Ok(Err(e)) => {
                // Specific error from the SSH connection attempt
                let error_msg = match &e {
                    crate::ssh::tokio_client::Error::KeyAuthFailed => {
                        "Authentication failed. The private key was rejected by the server.".to_string()
                    }
                    crate::ssh::tokio_client::Error::PasswordWrong => {
                        "Password authentication failed.".to_string()
                    }
                    crate::ssh::tokio_client::Error::ServerCheckFailed => {
                        "Host key verification failed. The server's host key was not recognized or has changed.".to_string()
                    }
                    crate::ssh::tokio_client::Error::KeyInvalid(key_err) => {
                        format!("Failed to load SSH key: {key_err}. Please check the key file format and passphrase.")
                    }
                    crate::ssh::tokio_client::Error::AgentConnectionFailed => {
                        "Failed to connect to SSH agent. Please ensure SSH_AUTH_SOCK is set and the agent is running.".to_string()
                    }
                    crate::ssh::tokio_client::Error::AgentNoIdentities => {
                        "SSH agent has no identities. Please add your key to the agent using 'ssh-add'.".to_string()
                    }
                    crate::ssh::tokio_client::Error::AgentAuthenticationFailed => {
                        "SSH agent authentication failed.".to_string()
                    }
                    crate::ssh::tokio_client::Error::SshError(ssh_err) => {
                        format!("SSH connection error: {ssh_err}")
                    }
                    _ => {
                        format!("Failed to connect: {e}")
                    }
                };
                Err(anyhow::anyhow!(error_msg).context(e))
            }
            Err(_) => Err(anyhow::anyhow!(
                "Connection timeout after {} seconds. \
                     Please check if the host is reachable and SSH service is running.",
                connect_timeout.as_secs()
            )),
        };

        // SECURITY: Normalize timing to prevent timing attacks
        // Ensure all authentication attempts take at least 500ms to complete
        const MIN_AUTH_DURATION: Duration = Duration::from_millis(500);
        let elapsed = start_time.elapsed();
        if elapsed < MIN_AUTH_DURATION {
            tokio::time::sleep(MIN_AUTH_DURATION - elapsed).await;
        }

        result
    }

    /// Create an SSH connection through jump hosts
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn connect_via_jump_hosts(
        &self,
        jump_hosts: &[crate::jump::parser::JumpHost],
        auth_method: &AuthMethod,
        strict_mode: StrictHostKeyChecking,
        key_path: Option<&Path>,
        use_agent: bool,
        use_password: bool,
        connect_timeout_seconds: Option<u64>,
        ssh_connection_config: Option<&SshConnectionConfig>,
    ) -> Result<Client> {
        // Create jump host chain with user-specified or default connect timeout
        let connect_timeout =
            Duration::from_secs(connect_timeout_seconds.unwrap_or(SSH_CONNECT_TIMEOUT_SECS));
        let mut chain = JumpHostChain::new(jump_hosts.to_vec())
            .with_connect_timeout(connect_timeout)
            .with_command_timeout(Duration::from_secs(300));
        if let Some(cfg) = ssh_connection_config {
            chain = chain.with_ssh_connection_config(cfg.clone());
        }

        // Connect through the chain
        let connection = chain
            .connect(
                &self.host,
                self.port,
                &self.username,
                auth_method.clone(),
                key_path,
                Some(strict_mode),
                use_agent,
                use_password,
            )
            .await
            .with_context(|| {
                format!(
                    "Failed to establish jump host connection to {}:{}",
                    self.host, self.port
                )
            })?;

        tracing::info!(
            "Jump host connection established: {}",
            connection.jump_info.path_description()
        );

        Ok(connection.client)
    }

    /// Establish a connection based on configuration (direct or via jump hosts)
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn establish_connection(
        &self,
        auth_method: &AuthMethod,
        strict_mode: StrictHostKeyChecking,
        jump_hosts_spec: Option<&str>,
        key_path: Option<&Path>,
        use_agent: bool,
        use_password: bool,
        connect_timeout_seconds: Option<u64>,
        ssh_connection_config: Option<&SshConnectionConfig>,
    ) -> Result<Client> {
        if let Some(jump_spec) = jump_hosts_spec {
            // Parse jump hosts
            let jump_hosts = parse_jump_hosts(jump_spec).with_context(|| {
                format!("Failed to parse jump host specification: '{jump_spec}'")
            })?;

            if jump_hosts.is_empty() {
                tracing::debug!("No valid jump hosts found, using direct connection");
                self.connect_direct(
                    auth_method,
                    strict_mode,
                    connect_timeout_seconds,
                    ssh_connection_config,
                )
                .await
            } else {
                tracing::info!(
                    "Connecting to {}:{} via {} jump host(s): {}",
                    self.host,
                    self.port,
                    jump_hosts.len(),
                    jump_hosts
                        .iter()
                        .map(|j| j.to_string())
                        .collect::<Vec<_>>()
                        .join(" -> ")
                );

                self.connect_via_jump_hosts(
                    &jump_hosts,
                    auth_method,
                    strict_mode,
                    key_path,
                    use_agent,
                    use_password,
                    connect_timeout_seconds,
                    ssh_connection_config,
                )
                .await
            }
        } else {
            // Direct connection
            tracing::debug!("Using direct connection (no jump hosts)");
            self.connect_direct(
                auth_method,
                strict_mode,
                connect_timeout_seconds,
                ssh_connection_config,
            )
            .await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::EnvGuard;
    use serial_test::serial;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_determine_auth_method_with_key() {
        let temp_dir = TempDir::new().unwrap();
        let key_path = temp_dir.path().join("test_key");
        std::fs::write(&key_path, "fake key content").unwrap();

        let client = SshClient::new("test.com".to_string(), 22, "user".to_string());
        let auth = client
            .determine_auth_method(
                Some(&key_path),
                false,
                false,
                #[cfg(target_os = "macos")]
                false,
            )
            .await
            .unwrap();

        match auth {
            AuthMethod::PrivateKeyFile { key_file_path, .. } => {
                // Path should be canonicalized now
                assert!(key_file_path.is_absolute());
            }
            _ => panic!("Expected PrivateKeyFile auth method"),
        }
    }

    #[cfg(target_os = "macos")]
    #[tokio::test]
    #[serial]
    async fn test_determine_auth_method_with_agent() {
        use std::os::unix::net::UnixListener;

        // Create a temporary directory for the socket and SSH keys
        let temp_dir = TempDir::new().unwrap();
        let socket_path = temp_dir.path().join("ssh-agent.sock");

        // Create a real Unix domain socket (required on macOS)
        // Note: This is a fake socket that doesn't implement SSH agent protocol
        let _listener = UnixListener::bind(&socket_path).unwrap();

        // Create a fake SSH key for fallback (since our fake agent has no identities)
        let ssh_dir = temp_dir.path().join(".ssh");
        std::fs::create_dir_all(&ssh_dir).unwrap();
        let key_content =
            "-----BEGIN PRIVATE KEY-----\nfake key content\n-----END PRIVATE KEY-----";
        std::fs::write(ssh_dir.join("id_rsa"), key_content).unwrap();

        // Guards restore prior values on drop.
        let _sock = EnvGuard::set("SSH_AUTH_SOCK", socket_path.to_str().unwrap());
        let _home = EnvGuard::set("HOME", temp_dir.path());

        let client = SshClient::new("test.com".to_string(), 22, "user".to_string());
        let auth = client
            .determine_auth_method(
                None,
                true,
                false,
                #[cfg(target_os = "macos")]
                false,
            )
            .await
            .unwrap();

        // With the agent identity check, if the agent has no identities (our fake socket),
        // it will fall back to key file authentication. Accept either outcome.
        match auth {
            AuthMethod::Agent => {
                // Real SSH agent with identities was found
            }
            AuthMethod::PrivateKeyFile { .. } => {
                // Fallback to key file (expected with fake socket)
            }
            _ => panic!("Expected Agent or PrivateKeyFile auth method"),
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    #[serial]
    async fn test_determine_auth_method_with_agent() {
        use std::os::unix::net::UnixListener;

        // Create a temporary directory for the socket and SSH keys
        let temp_dir = TempDir::new().unwrap();
        let socket_path = temp_dir.path().join("ssh-agent.sock");

        // Create a real Unix domain socket (required on Linux)
        // Note: This is a fake socket that doesn't implement SSH agent protocol
        let _listener = UnixListener::bind(&socket_path).unwrap();

        // Create a fake SSH key for fallback (since our fake agent has no identities)
        let ssh_dir = temp_dir.path().join(".ssh");
        std::fs::create_dir_all(&ssh_dir).unwrap();
        let key_content =
            "-----BEGIN PRIVATE KEY-----\nfake key content\n-----END PRIVATE KEY-----";
        std::fs::write(ssh_dir.join("id_rsa"), key_content).unwrap();

        // Guards restore prior values on drop.
        let _sock = EnvGuard::set("SSH_AUTH_SOCK", socket_path.to_str().unwrap());
        let _home = EnvGuard::set("HOME", temp_dir.path());

        let client = SshClient::new("test.com".to_string(), 22, "user".to_string());
        let auth = client
            .determine_auth_method(None, true, false)
            .await
            .unwrap();

        // With the agent identity check, if the agent has no identities (our fake socket),
        // it will fall back to key file authentication. Accept either outcome.
        match auth {
            AuthMethod::Agent => {
                // Real SSH agent with identities was found
            }
            AuthMethod::PrivateKeyFile { .. } => {
                // Fallback to key file (expected with fake socket)
            }
            _ => panic!("Expected Agent or PrivateKeyFile auth method"),
        }
    }

    #[test]
    fn test_determine_auth_method_with_password() {
        let _client = SshClient::new("test.com".to_string(), 22, "user".to_string());

        // Note: We can't actually test password prompt in unit tests
        // as it requires terminal input. This would need integration testing.
        // For now, we just verify the function compiles with the new parameter.
    }

    #[tokio::test]
    #[serial]
    async fn test_determine_auth_method_fallback_to_default() {
        // Create a fake home directory with default key
        let temp_dir = TempDir::new().unwrap();
        let ssh_dir = temp_dir.path().join(".ssh");
        std::fs::create_dir_all(&ssh_dir).unwrap();
        let default_key = ssh_dir.join("id_rsa");
        std::fs::write(&default_key, "fake key").unwrap();

        // Guards restore prior values on drop.
        let _home = EnvGuard::set("HOME", temp_dir.path().to_str().unwrap());
        let _sock = EnvGuard::remove("SSH_AUTH_SOCK");

        let client = SshClient::new("test.com".to_string(), 22, "user".to_string());
        let auth = client
            .determine_auth_method(
                None,
                false,
                false,
                #[cfg(target_os = "macos")]
                false,
            )
            .await
            .unwrap();

        match auth {
            AuthMethod::PrivateKeyFile { key_file_path, .. } => {
                // Path should be canonicalized now
                assert!(key_file_path.is_absolute());
            }
            _ => panic!("Expected PrivateKeyFile auth method"),
        }
    }
}