Skip to main content

fynx_proto/ssh/forwarding/
dynamic.rs

1//! Dynamic port forwarding (SOCKS5 proxy).
2//!
3//! Creates a SOCKS5 proxy server that dynamically forwards connections
4//! through the SSH tunnel based on the SOCKS5 protocol.
5//!
6//! # How it works
7//!
8//! 1. Listen on local address as SOCKS5 proxy
9//! 2. Client connects and performs SOCKS5 handshake
10//! 3. Extract target host and port from SOCKS5 request
11//! 4. Open SSH channel (`direct-tcpip`) to target
12//! 5. Relay data bidirectionally
13//!
14//! # Example
15//!
16//! ```rust,no_run
17//! use fynx_proto::ssh::client::SshClient;
18//!
19//! # #[tokio::main]
20//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
21//! let mut client = SshClient::connect("server:22").await?;
22//! client.authenticate_password("user", "pass").await?;
23//!
24//! // Create SOCKS5 proxy on localhost:1080
25//! let mut proxy = client.dynamic_forward("localhost:1080").await?;
26//!
27//! // Run proxy
28//! proxy.run().await?;
29//! # Ok(())
30//! # }
31//! ```
32
33use super::types::ForwardAddr;
34use crate::ssh::connection_mgr::SshConnection;
35use crate::ssh::dispatcher::MessageDispatcher;
36use fynx_platform::{FynxError, FynxResult};
37use std::sync::Arc;
38use tokio::io::{AsyncReadExt, AsyncWriteExt};
39use tokio::net::{TcpListener, TcpStream};
40use tokio::sync::Mutex;
41use tracing::{debug, info, warn};
42
43/// Dynamic port forwarding (SOCKS5 proxy) handle.
44///
45/// Created by [`SshClient::dynamic_forward()`](crate::ssh::client::SshClient::dynamic_forward).
46pub struct DynamicForward {
47    /// TCP listener for SOCKS5 connections
48    listener: TcpListener,
49    /// Local bind address
50    local_addr: ForwardAddr,
51    /// SSH connection (for opening channels)
52    connection: Arc<Mutex<SshConnection>>,
53    /// Message dispatcher (for channel communication)
54    dispatcher: Arc<Mutex<MessageDispatcher>>,
55    /// Connection counter
56    connection_counter: Arc<Mutex<u64>>,
57}
58
59impl DynamicForward {
60    /// Creates a new dynamic forward (SOCKS5 proxy).
61    ///
62    /// This is called by `SshClient::dynamic_forward()`.
63    ///
64    /// # Arguments
65    ///
66    /// * `listener` - TCP listener for SOCKS5 connections
67    /// * `local_addr` - Local address (for logging)
68    /// * `connection` - SSH connection for opening channels
69    /// * `dispatcher` - Message dispatcher for channel communication
70    pub(crate) fn new(
71        listener: TcpListener,
72        local_addr: ForwardAddr,
73        connection: Arc<Mutex<SshConnection>>,
74        dispatcher: Arc<Mutex<MessageDispatcher>>,
75    ) -> Self {
76        Self {
77            listener,
78            local_addr,
79            connection,
80            dispatcher,
81            connection_counter: Arc::new(Mutex::new(0)),
82        }
83    }
84
85    /// Returns the local address the SOCKS5 proxy is listening on.
86    pub fn local_addr(&self) -> &ForwardAddr {
87        &self.local_addr
88    }
89
90    /// Runs the SOCKS5 proxy.
91    ///
92    /// This method will accept connections and handle SOCKS5 protocol.
93    pub async fn run(self) -> FynxResult<()> {
94        info!("SOCKS5 proxy listening on {}", self.local_addr.to_string());
95
96        loop {
97            // Accept incoming SOCKS5 connection
98            let (socks_stream, peer_addr) = match self.listener.accept().await {
99                Ok((stream, addr)) => (stream, addr),
100                Err(e) => {
101                    warn!("Failed to accept SOCKS5 connection: {}", e);
102                    continue;
103                }
104            };
105
106            debug!("Accepted SOCKS5 connection from {}", peer_addr);
107
108            // Increment connection counter
109            let connection_id = {
110                let mut counter = self.connection_counter.lock().await;
111                *counter += 1;
112                *counter
113            };
114
115            // Clone Arc references for the spawned task
116            let connection = Arc::clone(&self.connection);
117            let dispatcher = Arc::clone(&self.dispatcher);
118
119            // Spawn task to handle this connection
120            tokio::spawn(async move {
121                if let Err(e) = Self::handle_socks_connection(
122                    connection_id,
123                    socks_stream,
124                    connection,
125                    dispatcher,
126                )
127                .await
128                {
129                    warn!("[SOCKS #{}] Error: {}", connection_id, e);
130                }
131            });
132        }
133    }
134
135    /// Handles a single SOCKS5 connection.
136    async fn handle_socks_connection(
137        connection_id: u64,
138        mut socks_stream: TcpStream,
139        connection: Arc<Mutex<SshConnection>>,
140        dispatcher: Arc<Mutex<MessageDispatcher>>,
141    ) -> FynxResult<()> {
142        use crate::ssh::channel::{ChannelMessage, SshChannel};
143        use crate::ssh::connection::{
144            ChannelData, ChannelOpen, ChannelType, MAX_PACKET_SIZE, MAX_WINDOW_SIZE,
145        };
146
147        // Perform SOCKS5 handshake to get target address
148        let (target_host, target_port) = match Self::socks5_handshake(&mut socks_stream).await {
149            Ok(target) => target,
150            Err(e) => {
151                warn!("[SOCKS #{}] Handshake failed: {}", connection_id, e);
152                let _ = Self::socks5_send_error(&mut socks_stream, 1).await;
153                return Err(e);
154            }
155        };
156
157        info!(
158            "[SOCKS #{}] Target: {}:{}",
159            connection_id, target_host, target_port
160        );
161
162        // Allocate channel ID and create channel
163        let (local_id, mut channel, tx) = {
164            let mut conn = connection.lock().await;
165            let local_id = conn.allocate_channel_id();
166            let (channel, tx) = SshChannel::with_channels(
167                local_id,
168                0, // remote_id will be set after confirmation
169                MAX_WINDOW_SIZE,
170                MAX_PACKET_SIZE,
171            );
172            (local_id, channel, tx)
173        };
174
175        // Register channel with dispatcher
176        dispatcher.lock().await.register_channel(local_id, tx).await;
177
178        // Send CHANNEL_OPEN (direct-tcpip) message
179        let channel_open = ChannelOpen::new(
180            ChannelType::DirectTcpip {
181                host: target_host.clone(),
182                port: target_port as u32,
183                originator_address: "127.0.0.1".to_string(), // SOCKS5 client is local
184                originator_port: 0,                          // Unknown SOCKS5 client port
185            },
186            local_id,
187            MAX_WINDOW_SIZE,
188            MAX_PACKET_SIZE,
189        );
190        let open_msg = channel_open.to_bytes();
191
192        {
193            let mut conn = connection.lock().await;
194            conn.send_packet(&open_msg).await?;
195        }
196
197        // Send SOCKS5 success response
198        if let Err(e) = Self::socks5_send_success(&mut socks_stream).await {
199            warn!("[SOCKS #{}] Failed to send success: {}", connection_id, e);
200            dispatcher.lock().await.unregister_channel(local_id).await;
201            return Err(e);
202        }
203
204        info!("[SOCKS #{}] Channel {} opened", connection_id, local_id);
205
206        // Bidirectional relay between SOCKS client and SSH channel
207        let (mut socks_read, mut socks_write) = tokio::io::split(socks_stream);
208        let remote_id = channel.remote_id();
209
210        let shutdown = Arc::new(tokio::sync::Notify::new());
211        let shutdown_upload = Arc::clone(&shutdown);
212        let shutdown_download = Arc::clone(&shutdown);
213
214        // Upload: SOCKS client -> SSH channel
215        let connection_upload = Arc::clone(&connection);
216        let upload_task = tokio::spawn(async move {
217            let mut buf = vec![0u8; 32768];
218            loop {
219                match socks_read.read(&mut buf).await {
220                    Ok(0) => {
221                        debug!("[SOCKS #{}] Client EOF", connection_id);
222                        break;
223                    }
224                    Ok(n) => {
225                        let channel_data = ChannelData::new(remote_id, buf[..n].to_vec());
226                        let data_msg = channel_data.to_bytes();
227
228                        let mut conn = connection_upload.lock().await;
229                        if let Err(e) = conn.send_packet(&data_msg).await {
230                            warn!("[SOCKS #{}] Failed to send data: {}", connection_id, e);
231                            break;
232                        }
233                    }
234                    Err(e) => {
235                        warn!("[SOCKS #{}] Client read error: {}", connection_id, e);
236                        break;
237                    }
238                }
239            }
240            shutdown_upload.notify_one();
241        });
242
243        // Download: SSH channel -> SOCKS client
244        let download_task = tokio::spawn(async move {
245            loop {
246                match channel.read().await {
247                    Ok(Some(ChannelMessage::Data(data))) => {
248                        if let Err(e) = socks_write.write_all(&data).await {
249                            warn!("[SOCKS #{}] Client write error: {}", connection_id, e);
250                            break;
251                        }
252                    }
253                    Ok(Some(ChannelMessage::Eof)) | Ok(Some(ChannelMessage::Close)) => {
254                        debug!("[SOCKS #{}] SSH channel EOF/Close", connection_id);
255                        break;
256                    }
257                    Ok(Some(_)) => {}
258                    Ok(None) => {
259                        warn!("[SOCKS #{}] Channel in legacy mode", connection_id);
260                        break;
261                    }
262                    Err(e) => {
263                        warn!("[SOCKS #{}] Channel read error: {}", connection_id, e);
264                        break;
265                    }
266                }
267            }
268            shutdown_download.notify_one();
269        });
270
271        // Wait for either task to complete
272        shutdown.notified().await;
273
274        upload_task.abort();
275        download_task.abort();
276
277        // Unregister channel
278        dispatcher.lock().await.unregister_channel(local_id).await;
279
280        info!("[SOCKS #{}] Connection closed", connection_id);
281
282        Ok(())
283    }
284
285    /// Handles SOCKS5 handshake and returns target address.
286    ///
287    /// # SOCKS5 Protocol
288    ///
289    /// ```text
290    /// Client → Server: [version, nmethods, methods...]
291    /// Server → Client: [version, method]
292    /// Client → Server: [version, command, reserved, address_type, address, port]
293    /// Server → Client: [version, status, reserved, address_type, address, port]
294    /// ```
295    async fn socks5_handshake(stream: &mut TcpStream) -> FynxResult<(String, u16)> {
296        // Read greeting: [version, nmethods, methods...]
297        let mut buf = [0u8; 257];
298        stream.read_exact(&mut buf[..2]).await?;
299
300        if buf[0] != 5 {
301            return Err(FynxError::Protocol(format!(
302                "Invalid SOCKS version: expected 5, got {}",
303                buf[0]
304            )));
305        }
306
307        let nmethods = buf[1] as usize;
308        if nmethods == 0 {
309            return Err(FynxError::Protocol(
310                "No authentication methods provided".to_string(),
311            ));
312        }
313
314        stream.read_exact(&mut buf[..nmethods]).await?;
315
316        // Send method selection: [version, method]
317        // 0x00 = no authentication required
318        stream.write_all(&[5, 0]).await?;
319
320        // Read request: [version, command, reserved, address_type, ...]
321        stream.read_exact(&mut buf[..4]).await?;
322
323        if buf[0] != 5 {
324            return Err(FynxError::Protocol(
325                "Invalid SOCKS version in request".to_string(),
326            ));
327        }
328
329        if buf[1] != 1 {
330            // CONNECT command
331            return Err(FynxError::Protocol(format!(
332                "Unsupported SOCKS command: {} (only CONNECT supported)",
333                buf[1]
334            )));
335        }
336
337        // Parse target address
338        let address_type = buf[3];
339        let (host, port) = match address_type {
340            1 => {
341                // IPv4
342                stream.read_exact(&mut buf[..6]).await?;
343                let ip = format!("{}.{}.{}.{}", buf[0], buf[1], buf[2], buf[3]);
344                let port = u16::from_be_bytes([buf[4], buf[5]]);
345                (ip, port)
346            }
347            3 => {
348                // Domain name
349                stream.read_exact(&mut buf[..1]).await?;
350                let len = buf[0] as usize;
351                stream.read_exact(&mut buf[..len + 2]).await?;
352                let host = String::from_utf8_lossy(&buf[..len]).to_string();
353                let port = u16::from_be_bytes([buf[len], buf[len + 1]]);
354                (host, port)
355            }
356            4 => {
357                // IPv6
358                stream.read_exact(&mut buf[..18]).await?;
359                let ip = format!(
360                    "{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}",
361                    buf[0], buf[1], buf[2], buf[3],
362                    buf[4], buf[5], buf[6], buf[7],
363                    buf[8], buf[9], buf[10], buf[11],
364                    buf[12], buf[13], buf[14], buf[15]
365                );
366                let port = u16::from_be_bytes([buf[16], buf[17]]);
367                (ip, port)
368            }
369            _ => {
370                return Err(FynxError::Protocol(format!(
371                    "Invalid address type: {}",
372                    address_type
373                )))
374            }
375        };
376
377        debug!("SOCKS5 request: {}:{}", host, port);
378
379        Ok((host, port))
380    }
381
382    /// Sends SOCKS5 success response.
383    async fn socks5_send_success(stream: &mut TcpStream) -> FynxResult<()> {
384        // [version, status, reserved, address_type, bound_address, bound_port]
385        // Status 0 = succeeded
386        stream
387            .write_all(&[
388                5, 0, 0, 1, // version, success, reserved, IPv4
389                0, 0, 0, 0, // Bound address (0.0.0.0)
390                0, 0, // Bound port (0)
391            ])
392            .await?;
393        Ok(())
394    }
395
396    /// Sends SOCKS5 error response.
397    async fn socks5_send_error(stream: &mut TcpStream, error_code: u8) -> FynxResult<()> {
398        // Common error codes:
399        // 0x01 = general failure
400        // 0x02 = connection not allowed by ruleset
401        // 0x03 = network unreachable
402        // 0x04 = host unreachable
403        // 0x05 = connection refused
404        stream
405            .write_all(&[
406                5, error_code, 0, 1, // version, error, reserved, IPv4
407                0, 0, 0, 0, // Bound address
408                0, 0, // Bound port
409            ])
410            .await?;
411        Ok(())
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    #[test]
420    fn test_forward_addr_dynamic() {
421        // Test ForwardAddr methods since we can't easily test DynamicForward
422        // without mocking connection and dispatcher
423        let local_addr = ForwardAddr::new("127.0.0.1".to_string(), 1080);
424
425        assert_eq!(local_addr.host, "127.0.0.1");
426        assert_eq!(local_addr.port, 1080);
427    }
428
429    // TODO: Add integration tests when full SOCKS5 support is complete
430    // Full tests require:
431    // 1. Mock or real SOCKS5 client
432    // 2. Connection and dispatcher setup
433    // 3. End-to-end SOCKS5 forwarding validation
434
435    // TODO: Add SOCKS5 protocol tests
436}