fynx_proto/ssh/forwarding/
dynamic.rs1use 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
43pub struct DynamicForward {
47 listener: TcpListener,
49 local_addr: ForwardAddr,
51 connection: Arc<Mutex<SshConnection>>,
53 dispatcher: Arc<Mutex<MessageDispatcher>>,
55 connection_counter: Arc<Mutex<u64>>,
57}
58
59impl DynamicForward {
60 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 pub fn local_addr(&self) -> &ForwardAddr {
87 &self.local_addr
88 }
89
90 pub async fn run(self) -> FynxResult<()> {
94 info!("SOCKS5 proxy listening on {}", self.local_addr.to_string());
95
96 loop {
97 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 let connection_id = {
110 let mut counter = self.connection_counter.lock().await;
111 *counter += 1;
112 *counter
113 };
114
115 let connection = Arc::clone(&self.connection);
117 let dispatcher = Arc::clone(&self.dispatcher);
118
119 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 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 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 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, MAX_WINDOW_SIZE,
170 MAX_PACKET_SIZE,
171 );
172 (local_id, channel, tx)
173 };
174
175 dispatcher.lock().await.register_channel(local_id, tx).await;
177
178 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(), originator_port: 0, },
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 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 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 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 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 shutdown.notified().await;
273
274 upload_task.abort();
275 download_task.abort();
276
277 dispatcher.lock().await.unregister_channel(local_id).await;
279
280 info!("[SOCKS #{}] Connection closed", connection_id);
281
282 Ok(())
283 }
284
285 async fn socks5_handshake(stream: &mut TcpStream) -> FynxResult<(String, u16)> {
296 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 stream.write_all(&[5, 0]).await?;
319
320 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 return Err(FynxError::Protocol(format!(
332 "Unsupported SOCKS command: {} (only CONNECT supported)",
333 buf[1]
334 )));
335 }
336
337 let address_type = buf[3];
339 let (host, port) = match address_type {
340 1 => {
341 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 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 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 async fn socks5_send_success(stream: &mut TcpStream) -> FynxResult<()> {
384 stream
387 .write_all(&[
388 5, 0, 0, 1, 0, 0, 0, 0, 0, 0, ])
392 .await?;
393 Ok(())
394 }
395
396 async fn socks5_send_error(stream: &mut TcpStream, error_code: u8) -> FynxResult<()> {
398 stream
405 .write_all(&[
406 5, error_code, 0, 1, 0, 0, 0, 0, 0, 0, ])
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 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 }