reverse-ssh 0.2.0

A Rust library for creating reverse SSH tunnels with automatic URL capture from services like localhost.run
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
use anyhow::{Context, Result};
use russh::client::{self, Handle, Msg};
use russh::keys::*;
use russh::*;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tracing::{debug, error, info, warn};

/// Configuration for the reverse SSH connection
#[derive(Debug, Clone)]
pub struct ReverseSshConfig {
    /// The SSH server address to connect to
    pub server_addr: String,
    /// The SSH server port
    pub server_port: u16,
    /// Username for SSH authentication
    pub username: String,
    /// Private key path for authentication
    pub key_path: Option<String>,
    /// Password for authentication (if not using key)
    pub password: Option<String>,
    /// Bind address for remote port forwarding.
    /// For services like pico.sh tuns, this is the tunnel name (e.g., "dev" -> "user-dev.tuns.sh").
    /// For localhost.run, use an empty string to let the server assign a random subdomain.
    /// Defaults to empty string if not specified.
    pub bind_address: String,
    /// Remote port to listen on (on the SSH server)
    pub remote_port: u32,
    /// Local address to forward connections to
    pub local_addr: String,
    /// Local port to forward connections to
    pub local_port: u16,
}

/// SSH client handler
struct Client {
    tx: mpsc::UnboundedSender<(Channel<Msg>, String, u32)>,
    message_tx: mpsc::UnboundedSender<String>,
}

#[async_trait::async_trait]
impl client::Handler for Client {
    type Error = russh::Error;

    async fn check_server_key(
        &mut self,
        _server_public_key: &key::PublicKey,
    ) -> Result<bool, Self::Error> {
        // In production, you should verify the server's public key
        // For now, we accept any key
        Ok(true)
    }

    async fn server_channel_open_forwarded_tcpip(
        &mut self,
        channel: Channel<Msg>,
        connected_address: &str,
        connected_port: u32,
        originator_address: &str,
        originator_port: u32,
        _session: &mut client::Session,
    ) -> Result<(), Self::Error> {
        debug!(
            "Forwarded channel: {}:{} -> {}:{}",
            originator_address, originator_port, connected_address, connected_port
        );

        // Send the channel to be handled
        let _ = self
            .tx
            .send((channel, connected_address.to_string(), connected_port));

        Ok(())
    }

    async fn data(
        &mut self,
        _channel: ChannelId,
        data: &[u8],
        _session: &mut client::Session,
    ) -> Result<(), Self::Error> {
        // Convert data to string and send it for processing
        // Don't filter out partial messages - send everything
        if let Ok(message) = String::from_utf8(data.to_vec()) {
            debug!("Received data ({} bytes): {}", data.len(), message);
            let _ = self.message_tx.send(message);
        } else {
            // Log if we received non-UTF8 data
            debug!(
                "Received {} bytes of non-UTF8 data on channel {:?}",
                data.len(),
                _channel
            );
        }
        Ok(())
    }

    async fn extended_data(
        &mut self,
        _channel: ChannelId,
        ext: u32,
        data: &[u8],
        _session: &mut client::Session,
    ) -> Result<(), Self::Error> {
        // Extended data includes stderr (ext == 1)
        // localhost.run sends URL info through stderr
        if let Ok(message) = String::from_utf8(data.to_vec()) {
            info!("Received extended data (type {}): {}", ext, message);
            let _ = self.message_tx.send(message);
        }
        debug!(
            "Received {} bytes of extended data (type {}) on channel {:?}",
            data.len(),
            ext,
            _channel
        );
        Ok(())
    }
}

impl Client {
    fn new(
        tx: mpsc::UnboundedSender<(Channel<Msg>, String, u32)>,
        message_tx: mpsc::UnboundedSender<String>,
    ) -> Self {
        Self { tx, message_tx }
    }
}

/// Reverse SSH client that establishes a reverse tunnel
pub struct ReverseSshClient {
    config: ReverseSshConfig,
    handle: Option<Handle<Client>>,
}

impl ReverseSshClient {
    /// Create a new reverse SSH client with the given configuration
    pub fn new(config: ReverseSshConfig) -> Self {
        Self {
            config,
            handle: None,
        }
    }

    /// Connect to the SSH server and authenticate
    pub async fn connect(
        &mut self,
        tx: mpsc::UnboundedSender<(Channel<Msg>, String, u32)>,
        message_tx: mpsc::UnboundedSender<String>,
    ) -> Result<()> {
        info!(
            "Connecting to SSH server {}:{}",
            self.config.server_addr, self.config.server_port
        );

        let client_config = client::Config {
            inactivity_timeout: Some(std::time::Duration::from_secs(3600)),
            ..<_>::default()
        };

        let client_handler = Client::new(tx, message_tx);

        let mut session = client::connect(
            Arc::new(client_config),
            (self.config.server_addr.as_str(), self.config.server_port),
            client_handler,
        )
        .await
        .context("Failed to connect to SSH server")?;

        // Authenticate
        let auth_result = if let Some(key_path) = &self.config.key_path {
            info!("Authenticating with private key: {}", key_path);
            let key_pair = russh_keys::load_secret_key(key_path, None)
                .context("Failed to load private key")?;
            session
                .authenticate_publickey(&self.config.username, Arc::new(key_pair))
                .await
        } else if let Some(password) = &self.config.password {
            info!("Authenticating with password");
            session
                .authenticate_password(&self.config.username, password)
                .await
        } else {
            anyhow::bail!("No authentication method provided (need key_path or password)");
        };

        if !auth_result.context("Authentication failed")? {
            anyhow::bail!("Authentication rejected by server");
        }

        info!("Successfully authenticated to SSH server");
        self.handle = Some(session);
        Ok(())
    }

    /// Set up a reverse port forward (remote port forwarding)
    /// This makes the SSH server listen on a port and forward connections back to us
    pub async fn setup_reverse_tunnel(&mut self) -> Result<()> {
        let handle = self
            .handle
            .as_mut()
            .context("Not connected - call connect() first")?;

        if self.config.bind_address.is_empty() {
            info!(
                "Setting up reverse tunnel: server port {} -> local {}:{}",
                self.config.remote_port, self.config.local_addr, self.config.local_port
            );
        } else {
            info!(
                "Setting up reverse tunnel: {}:{} -> local {}:{}",
                self.config.bind_address,
                self.config.remote_port,
                self.config.local_addr,
                self.config.local_port
            );
        }

        // Request remote port forwarding
        // The bind_address is used for services like pico.sh tuns where it becomes
        // the tunnel name (subdomain). For localhost.run, use empty string.
        handle
            .tcpip_forward(&self.config.bind_address, self.config.remote_port)
            .await
            .context("Failed to set up remote port forwarding")?;

        info!("Reverse tunnel established successfully");

        // Open a shell session to receive server messages (like the URL from localhost.run)
        // This is important for services that send connection info via shell
        match handle.channel_open_session().await {
            Ok(channel) => {
                info!("Opened shell session to receive server messages");
                // Request a shell - this triggers the server to send welcome messages
                if let Err(e) = channel.request_shell(false).await {
                    warn!("Failed to request shell: {}", e);
                } else {
                    debug!("Shell requested successfully");
                }
                // Don't close the channel - keep it open to receive messages
                // The channel will be kept alive by the handler
            }
            Err(e) => {
                warn!(
                    "Could not open shell session: {} (this may be normal for some servers)",
                    e
                );
            }
        }

        Ok(())
    }

    /// Read server messages (useful for services like localhost.run that send URL info)
    /// This opens a session channel and attempts to read any messages from the server
    #[allow(dead_code)]
    pub async fn read_server_messages(&mut self) -> Result<Vec<String>> {
        let handle = self
            .handle
            .as_mut()
            .context("Not connected - call connect() first")?;

        let mut messages = Vec::new();

        // Try to open a session channel to read any server messages
        match handle.channel_open_session().await {
            Ok(channel) => {
                // Request a shell to trigger server messages
                let _ = channel.request_shell(false).await;

                // Wait a bit for messages to arrive
                tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

                // Try to read data from the channel
                // Note: This is a simplified approach - in practice, we'd need to
                // handle the channel data in the Handler's data() method

                // Close the channel
                let _ = channel.eof().await;
                let _ = channel.close().await;

                messages.push("Check SSH session output for connection URL".to_string());
            }
            Err(e) => {
                warn!("Could not open session channel: {}", e);
            }
        }

        Ok(messages)
    }

    /// Handle forwarded connections from the SSH server
    pub async fn handle_forwarded_connections(
        &mut self,
        mut rx: mpsc::UnboundedReceiver<(Channel<Msg>, String, u32)>,
    ) -> Result<()> {
        info!("Waiting for forwarded connections...");

        while let Some((channel, _remote_addr, _remote_port)) = rx.recv().await {
            info!("New forwarded connection received");

            // Spawn a task to handle this connection
            let local_addr = self.config.local_addr.clone();
            let local_port = self.config.local_port;

            tokio::spawn(async move {
                if let Err(e) = handle_connection(channel, &local_addr, local_port).await {
                    error!("Error handling connection: {}", e);
                }
            });
        }

        warn!("Connection closed by server");
        Ok(())
    }

    /// Run the reverse SSH client (connect, setup tunnel, and handle connections)
    #[allow(dead_code)]
    pub async fn run(&mut self) -> Result<()> {
        let (tx, rx) = mpsc::unbounded_channel();
        let (message_tx, mut message_rx) = mpsc::unbounded_channel();

        self.connect(tx, message_tx).await?;
        self.setup_reverse_tunnel().await?;

        // Spawn a task to print server messages
        tokio::spawn(async move {
            while let Some(message) = message_rx.recv().await {
                // Print server messages, which may include URLs
                if !message.trim().is_empty() {
                    println!("[Server] {}", message.trim());
                }
            }
        });

        self.handle_forwarded_connections(rx).await?;

        Ok(())
    }

    /// Run the client with custom message handling
    pub async fn run_with_message_handler<F>(&mut self, mut message_handler: F) -> Result<()>
    where
        F: FnMut(String) + Send + 'static,
    {
        let (tx, rx) = mpsc::unbounded_channel();
        let (message_tx, mut message_rx) = mpsc::unbounded_channel();

        self.connect(tx, message_tx).await?;
        self.setup_reverse_tunnel().await?;

        // Spawn a task to handle server messages with custom handler
        tokio::spawn(async move {
            while let Some(message) = message_rx.recv().await {
                message_handler(message);
            }
        });

        self.handle_forwarded_connections(rx).await?;

        Ok(())
    }
}

/// Handle a single forwarded connection by proxying data between SSH channel and local service
async fn handle_connection(
    mut channel: Channel<Msg>,
    local_addr: &str,
    local_port: u16,
) -> Result<()> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    info!("Connecting to local service {}:{}", local_addr, local_port);

    // Connect to the local service
    let local_socket_addr: SocketAddr = format!("{}:{}", local_addr, local_port)
        .parse()
        .context("Invalid local address")?;

    let mut local_stream = TcpStream::connect(local_socket_addr)
        .await
        .context("Failed to connect to local service")?;

    info!("Connected to local service, starting bidirectional proxy");

    // Bidirectional proxy using tokio::select!
    let mut local_buf = vec![0u8; 8192];

    // Read from local and forward to SSH
    loop {
        tokio::select! {
            // Read from SSH channel and write to local service
            msg = channel.wait() => {
                match msg {
                    Some(russh::ChannelMsg::Data { data }) => {
                        debug!("Received {} bytes from SSH channel", data.len());
                        if let Err(e) = local_stream.write_all(&data).await {
                            error!("Failed to write to local service: {}", e);
                            break;
                        }
                    }
                    Some(russh::ChannelMsg::Eof) => {
                        debug!("Received EOF from SSH channel");
                        let _ = local_stream.shutdown().await;
                        break;
                    }
                    Some(russh::ChannelMsg::Close) => {
                        debug!("SSH channel closed");
                        break;
                    }
                    Some(other) => {
                        debug!("Received other channel message: {:?}", other);
                    }
                    None => {
                        debug!("SSH channel receiver closed");
                        break;
                    }
                }
            }

            // Read from local service and write to SSH channel
            result = local_stream.read(&mut local_buf) => {
                match result {
                    Ok(0) => {
                        debug!("Local connection closed");
                        break;
                    }
                    Ok(n) => {
                        debug!("Read {} bytes from local service", n);
                        if let Err(e) = channel.data(&local_buf[..n]).await {
                            error!("Failed to send data to SSH channel: {}", e);
                            break;
                        }
                    }
                    Err(e) => {
                        error!("Error reading from local service: {}", e);
                        break;
                    }
                }
            }
        }
    }

    // Close the channel gracefully
    let _ = channel.eof().await;
    let _ = channel.close().await;

    info!("Connection proxy closed");

    Ok(())
}

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

    #[test]
    fn test_config_creation() {
        let config = ReverseSshConfig {
            server_addr: "example.com".to_string(),
            server_port: 22,
            username: "user".to_string(),
            key_path: Some("/path/to/key".to_string()),
            password: None,
            bind_address: String::new(),
            remote_port: 8080,
            local_addr: "127.0.0.1".to_string(),
            local_port: 3000,
        };

        assert_eq!(config.server_addr, "example.com");
        assert_eq!(config.remote_port, 8080);
        assert!(config.bind_address.is_empty());
    }

    #[test]
    fn test_config_with_bind_address() {
        let config = ReverseSshConfig {
            server_addr: "tuns.sh".to_string(),
            server_port: 22,
            username: "myuser".to_string(),
            key_path: Some("/path/to/key".to_string()),
            password: None,
            bind_address: "dev".to_string(),
            remote_port: 80,
            local_addr: "127.0.0.1".to_string(),
            local_port: 8000,
        };

        assert_eq!(config.server_addr, "tuns.sh");
        assert_eq!(config.bind_address, "dev");
        assert_eq!(config.remote_port, 80);
    }
}