sshbind 0.1.0

SSHBind is a Rust library that securely binds remote services behind multiple SSH jump hosts to a local socket, enabling seamless access with encrypted credential management, TOTP-based two-factor authentication, and automatic reconnection.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use age::x25519;
use libreauth::oath::TOTPBuilder;
use secrecy::ExposeSecret;
use sshbind::YamlCreds;
use std::fs;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

/// Test cleanup handler that ensures resources are freed even on test failure
pub struct TestCleanup {
    pub ssh_tasks: Vec<tokio::task::AbortHandle>,
    pub service_handle: Option<tokio::task::AbortHandle>,
    pub bind_addr: String,
}

impl TestCleanup {
    pub fn new(bind_addr: String) -> Self {
        Self {
            ssh_tasks: Vec::new(),
            service_handle: None,
            bind_addr,
        }
    }

    pub fn add_ssh_task(&mut self, task: &tokio::task::JoinHandle<()>) {
        self.ssh_tasks.push(task.abort_handle());
    }

    pub fn set_service_handle(&mut self, handle: &tokio::task::JoinHandle<()>) {
        self.service_handle = Some(handle.abort_handle());
    }

    /// Perform cleanup - can be called explicitly or automatically on drop
    pub fn cleanup(&mut self) {
        use log::info;

        info!("Cleaning up test resources");

        // Unbind the address first
        sshbind::unbind(&self.bind_addr);

        // Abort all tasks
        for task in &self.ssh_tasks {
            task.abort();
        }
        if let Some(handle) = &self.service_handle {
            handle.abort();
        }

        // Clear the collections
        self.ssh_tasks.clear();
        self.service_handle = None;
    }
}

impl Drop for TestCleanup {
    fn drop(&mut self) {
        // Ensure cleanup happens even if test panics
        self.cleanup();
    }
}

/// Port generator for tests - each test gets a unique range
/// Base port starts at 10000 and each test gets a range based on jump host count
pub struct TestPorts {
    base: u16,
    jump_host_count: usize,
    jump_hosts: Vec<String>,
}

impl TestPorts {
    /// Create a new TestPorts instance with a unique test ID and number of jump hosts
    /// test_id should be unique per test (e.g., 1, 2, 3, etc.)
    /// jump_host_count is the number of SSH jump hosts this test needs
    pub fn new(test_id: u16, jump_host_count: usize) -> Self {
        // Each test gets a range of ports: bind(1) + jump_hosts(N) + service(1) + buffer(2)
        // So test needs (jump_host_count + 4) ports total
        let base = 10000 + (test_id * 10); // Still use 10-port ranges for simplicity

        // Generate jump host addresses
        let jump_hosts = (0..jump_host_count)
            .map(|i| format!("127.0.0.1:{}", base + 1 + (i as u16)))
            .collect();

        TestPorts {
            base,
            jump_host_count,
            jump_hosts,
        }
    }

    /// Get the bind address (always port 0 in range)
    pub fn bind_addr(&self) -> String {
        format!("127.0.0.1:{}", self.base)
    }

    /// Get the service address (always after all jump hosts)
    pub fn service_addr(&self) -> String {
        format!(
            "127.0.0.1:{}",
            self.base + 1 + (self.jump_host_count as u16)
        )
    }

    /// Get jump host addresses as a vector
    pub fn jump_hosts(&self) -> Vec<String> {
        self.jump_hosts.clone()
    }

    /// Get a specific jump host address by index
    pub fn jump_host(&self, index: usize) -> String {
        if index >= self.jump_host_count {
            panic!(
                "Jump host index {} out of range (max: {})",
                index,
                self.jump_host_count - 1
            );
        }
        self.jump_hosts[index].clone()
    }
}

pub fn setup_sopsfile(testcreds: YamlCreds) -> TempDir {
    let binding = std::env::current_dir().unwrap();
    let wd = binding.as_path();
    let tmp_dir = TempDir::new_in(wd).expect("Failed to create temp dir");
    info!("Temp dir: {:?}", tmp_dir.path());
    let file_path = tmp_dir.path().join("secrets.yaml");

    // Generate a new age key pair.
    let identity = x25519::Identity::generate();
    let public_key = identity.to_public();

    // Define file paths within the temporary directory.
    let key_path: PathBuf = tmp_dir.path().join("age_key.txt");
    let config_path: PathBuf = tmp_dir.path().join(".sops.yaml");

    // Write the private key to our temporary file.
    fs::write(&key_path, identity.to_string().expose_secret()).expect("Failed to write key");

    // Create a minimal SOPS configuration file.
    // Here we specify that for any YAML file, sops should use the given age public key.
    let config_content = format!("keys:\n  - &master {}\ncreation_rules:\n  - path_regex: secrets.yaml$\n    key_groups:\n    - age:\n      - *master", public_key);

    fs::write(&config_path, config_content).expect("Failed to write config");

    // Optionally, you can assert that the files exist in the temp dir.
    assert!(key_path.exists());
    assert!(config_path.exists());

    let stringified = serde_yml::to_string(&testcreds).expect("Failed to serialize");
    //
    // Write test configuration to the file
    fs::write(&file_path, stringified).expect("Failed to write to file");
    let path = file_path.to_str().unwrap();

    std::env::set_var("SOPS_AGE_KEY_FILE", key_path.to_str().unwrap());
    let _ = std::env::set_current_dir(tmp_dir.path());

    let output = Command::new("sops")
        .arg("encrypt")
        .arg(path) // user input as a separate argument
        .output()
        .expect("failed to execute process");

    let enc_content = String::from_utf8_lossy(&output.stdout).to_string();
    fs::write(&file_path, enc_content).expect("Failed to write to file");

    info!("Temp Credential Directory prepared");
    tmp_dir
}

use async_trait::async_trait;
use log::{error, info};
use russh::keys::PublicKey;
use russh::server::{Auth, Handler, Response, Server, Session};
use russh::Channel;
use std::borrow::Cow;
use std::collections::HashMap;
use tokio::net::TcpStream;

///
/// Credentials and SSHServer state.
///
#[derive(Clone, Debug)]
pub struct Credentials {
    pub password: String,
    pub require_2fa: bool,
    pub two_factor_code: Option<String>,
    pub allowed_pubkey_base64: Option<String>,
}

impl From<sshbind::Creds> for Credentials {
    fn from(creds: sshbind::Creds) -> Self {
        if let Some(ref totp_key) = creds.totp_key {
            #[allow(clippy::needless_return)]
            return Credentials {
                password: creds.password.clone(),
                require_2fa: true,
                two_factor_code: Some(totp_key.clone()),
                allowed_pubkey_base64: None,
            };
        } else {
            #[allow(clippy::needless_return)]
            return Credentials {
                password: creds.password.clone(),
                require_2fa: false,
                two_factor_code: None,
                allowed_pubkey_base64: None,
            };
        };
    }
}

#[derive(Clone)]
pub struct SSHServer {
    pub users: HashMap<String, Credentials>,
}

impl SSHServer {
    pub fn new(users: Option<HashMap<String, Credentials>>) -> Self {
        if let Some(users) = users {
            SSHServer { users }
        } else {
            let mut users = HashMap::new();
            users.insert(
                "test".to_string(),
                Credentials {
                    password: "password".to_string(),
                    require_2fa: true,
                    two_factor_code: Some("123456".to_string()),
                    allowed_pubkey_base64: None,
                },
            );
            SSHServer { users }
        }
    }
}

impl Server for SSHServer {
    type Handler = SSHServer;

    // For each new client, we simply return a clone of our handler.
    fn new_client(&mut self, _peer_addr: Option<SocketAddr>) -> Self::Handler {
        self.clone()
    }

    // Log any session errors.
    fn handle_session_error(&mut self, error: <Self::Handler as Handler>::Error) {
        eprintln!("Session error: {}", error);
    }
}

///
/// Handler implementation for SSHServer.
///
#[async_trait]
impl Handler for SSHServer {
    type Error = Box<dyn std::error::Error + Send + Sync>;

    #[allow(clippy::manual_async_fn)]
    fn auth_password(
        &mut self,
        user: &str,
        password: &str,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        async move {
            info!("auth_password: user={} password={}", user, password);
            if let Some(cred) = self.users.get(user) {
                if cred.password == password {
                    if cred.require_2fa {
                        info!("Password valid but 2FA required for user {}", user);
                        return Ok(Auth::Partial {
                            name: "".into(),
                            instructions: "2FA required".into(),
                            prompts: vec![(Cow::from("Enter 2FA code: "), false)].into(),
                        });
                    }
                    info!("Password authentication accepted for user {}", user);
                    return Ok(Auth::Accept);
                }
            }
            error!("Password authentication rejected for user: {}", user);
            Ok(Auth::Reject {
                proceed_with_methods: None,
                partial_success: false,
            })
        }
    }

    #[allow(clippy::manual_async_fn)]
    fn auth_publickey(
        &mut self,
        user: &str,
        public_key: &PublicKey,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        async move {
            info!("auth_publickey: user={}", user);
            if let Some(cred) = self.users.get(user) {
                if let Some(ref allowed) = cred.allowed_pubkey_base64 {
                    if allowed == &public_key.to_string() {
                        if cred.require_2fa {
                            info!("Public key valid but 2FA required for user {}", user);
                            return Ok(Auth::Partial {
                                name: "".into(),
                                instructions: "2FA required".into(),
                                prompts: vec![(Cow::from("Enter 2FA code: "), false)].into(),
                            });
                        }
                        info!("Public key authentication accepted for user {}", user);
                        return Ok(Auth::Accept);
                    }
                }
            }
            error!("Public key authentication rejected for user: {}", user);
            Ok(Auth::Reject {
                proceed_with_methods: None,
                partial_success: false,
            })
        }
    }

    #[allow(clippy::manual_async_fn)]
    fn auth_keyboard_interactive<'a>(
        &'a mut self,
        user: &str,
        submethods: &str,
        response: Option<Response<'a>>,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        async move {
            info!(
                "auth_keyboard_interactive: user={} submethods={}",
                user, submethods
            );
            if let Some(cred) = self.users.get(user) {
                if !cred.require_2fa {
                    return Ok(Auth::Accept);
                }
                if response.is_none() {
                    info!("2FA required for user {}", user);
                    return Ok(Auth::Partial {
                        name: "".into(),
                        instructions: "2FA required".into(),
                        prompts: vec![
                            (Cow::from("Password: "), false),
                            (Cow::from("Enter 2FA code: "), false),
                        ]
                        .into(),
                    });
                } else {
                    info!("Else");
                    let responses: Vec<String> = response
                        .unwrap()
                        .filter_map(|b| String::from_utf8(b.to_vec()).ok())
                        .collect();
                    info!("2FA response: {:?}", responses);

                    let password = responses
                        .first()
                        .map(|s| s.trim().to_string())
                        .unwrap_or_default();
                    let otp_code = responses
                        .get(1)
                        .map(|s| s.trim().to_string())
                        .unwrap_or_default();

                    let ref_code = match cred.two_factor_code.as_ref() {
                        Some(key) => TOTPBuilder::new().base32_key(key).finalize()?.generate(),
                        None => "".to_string(),
                    };
                    if password != cred.password {
                        error!("Invalid password provided by user {}", user);
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }
                    if otp_code != ref_code {
                        error!("Invalid 2FA code provided by user {}", user);
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }

                    info!("2FA accepted for user {}", user);
                    return Ok(Auth::Accept);
                }
            } else if response.is_none() {
                info!("2FA required for user {}", user);
                return Ok(Auth::Partial {
                    name: "".into(),
                    instructions: "2FA required".into(),
                    prompts: vec![
                        (Cow::from("Username: "), true),
                        (Cow::from("Password: "), false),
                        (Cow::from("Enter 2FA code: "), false),
                    ]
                    .into(),
                });
            } else {
                let responses: Vec<String> = response
                    .unwrap()
                    .filter_map(|b| String::from_utf8(b.to_vec()).ok())
                    .collect();
                info!("2FA response: {:?}", responses);

                let username = responses
                    .first()
                    .map(|s| s.trim().to_string())
                    .unwrap_or_default();
                let password = responses
                    .get(1)
                    .map(|s| s.trim().to_string())
                    .unwrap_or_default();
                let otp_code = responses
                    .get(2)
                    .map(|s| s.trim().to_string())
                    .unwrap_or_default();
                if let Some(creds) = self.users.get(&username) {
                    let ref_code = match creds.two_factor_code.as_ref() {
                        Some(key) => TOTPBuilder::new().base32_key(key).finalize()?.generate(),
                        None => "".to_string(),
                    };
                    if password != creds.password {
                        error!("Invalid password provided by user {}", user);
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }
                    if otp_code != ref_code {
                        error!("Invalid 2FA code provided by user {}", user);
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }
                    info!("2FA accepted for user {}", user);
                    return Ok(Auth::Accept);
                }
            }
            error!("User {} not found in keyboard interactive auth", user);
            Ok(Auth::Reject {
                proceed_with_methods: None,
                partial_success: false,
            })
        }
    }

    #[allow(unused_variables, clippy::manual_async_fn)]
    fn channel_open_session(
        &mut self,
        channel: Channel<russh::server::Msg>,
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
        async move {
            info!("Session channel opened: {:?}", channel);
            Ok(true)
        }
    }

    #[allow(unused_mut, clippy::manual_async_fn)]
    fn channel_open_direct_tcpip(
        &mut self,
        mut channel: Channel<russh::server::Msg>,
        host_to_connect: &str,
        port_to_connect: u32,
        _originator_address: &str,
        _originator_port: u32,
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
        async move {
            info!(
                "Direct TCP/IP channel request to {}:{}",
                host_to_connect, port_to_connect
            );
            if host_to_connect != "127.0.0.1" && host_to_connect != "localhost" {
                error!(
                    "Rejected direct TCP/IP channel: target {} not allowed",
                    host_to_connect
                );
                return Ok(false);
            }
            let port: u16 = port_to_connect as u16;
            match TcpStream::connect((host_to_connect, port)).await {
                Ok(mut target_stream) => {
                    // Signal that the channel connection was successful.
                    session.channel_success(channel.id())?;
                    info!("Channel confirmed");
                    // use russh::channels::channel_stream::ChannelStream;
                    // let mut chan_stream = ChannelStream::new(channel);
                    let mut chan_stream = channel.into_stream();

                    // Spawn a task to relay data between the channel and target stream.
                    tokio::spawn(async move {
                        if let Err(e) =
                            tokio::io::copy_bidirectional(&mut target_stream, &mut chan_stream)
                                .await
                        {
                            error!("Forwarding error: {}", e);
                        }
                    });
                    Ok(true)
                }
                Err(e) => {
                    error!(
                        "Failed to connect to target {}:{} - {}",
                        host_to_connect, port, e
                    );
                    Ok(false)
                }
            }
        }
    }
}