wsproxy 0.1.3

WebSocket proxy for TCP connections
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
//! WebSocket Proxy Client
//!
//! Listens for TCP connections and forwards data through WebSocket to a server.

use std::net::SocketAddr;
use std::sync::Arc;

use futures_util::{SinkExt, StreamExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message;

use crate::error::{Error, Result};
use crate::server::{Bindable, IntoBindable};

/// TLS options for the client
#[derive(Debug, Clone, Default)]
pub struct TlsOptions {
    /// Skip certificate verification (insecure, for self-signed certificates)
    pub insecure: bool,
    /// Path to CA certificate file (PEM format) for verifying self-signed server certificates
    pub ca_cert_path: Option<String>,
}

/// Run a proxy client with the given configuration.
///
/// This is a convenience function that builds and runs a `ProxyClient`.
///
/// # Arguments
///
/// * `listen` - Address to listen for TCP connections (e.g., "127.0.0.1:2222")
/// * `server_url` - WebSocket server URL to connect to (e.g., "ws://server:8080/ssh")
/// * `tls_options` - TLS options for certificate verification
///
/// # Example
///
/// ```no_run
/// # async fn example() -> wsproxy::Result<()> {
/// wsproxy::client::run("127.0.0.1:2222", "ws://server:8080/ssh", &Default::default()).await?;
/// # Ok(())
/// # }
/// ```
pub async fn run(listen: &str, server_url: &str, tls_options: &TlsOptions) -> Result<()> {
    let client = ProxyClient::bind(listen, server_url, tls_options.clone())?;

    eprintln!(
        "Proxy client listening on {}, forwarding to {}",
        listen, server_url
    );

    client.run().await
}

/// Run a single tunnel connection using stdin/stdout.
///
/// This is useful for SSH ProxyCommand integration. The tunnel connects to
/// the WebSocket server and forwards data between stdin/stdout and the WebSocket.
///
/// # Arguments
///
/// * `server_url` - WebSocket server URL to connect to (e.g., "ws://server:8080/ssh")
/// * `tls_options` - TLS options for certificate verification
///
/// # Example SSH Config
///
/// ```text
/// Host myserver
///   ProxyCommand wsproxy tunnel --server wss://proxy:8080/ssh
///   User myuser
///   HostName localhost
/// ```
pub async fn tunnel(server_url: &str, tls_options: &TlsOptions) -> Result<()> {
    use tokio::io::{stdin, stdout};
    // Connect to WebSocket server
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;

    let request = server_url.into_client_request()?;
    let uri = request.uri();
    let scheme = uri.scheme_str().unwrap_or("ws");
    let host = uri
        .host()
        .ok_or_else(|| Error::config("missing host in URL"))?;
    let port = uri
        .port_u16()
        .unwrap_or(if scheme == "wss" { 443 } else { 80 });

    let addr = format!("{}:{}", host, port);
    let tcp_conn = TcpStream::connect(&addr).await?;

    if scheme == "wss" {
        // TLS connection
        use tokio_rustls::rustls::pki_types::ServerName;

        let config = build_tls_config(tls_options)?;

        let connector = tokio_rustls::TlsConnector::from(Arc::new(config));
        let server_name = ServerName::try_from(host.to_string())
            .map_err(|e| Error::config(format!("invalid server name: {}", e)))?;

        let tls_stream = connector.connect(server_name, tcp_conn).await?;
        let (ws_stream, _response) = tokio_tungstenite::client_async(request, tls_stream).await?;
        forward_ws_stdio(ws_stream, stdin(), stdout()).await
    } else {
        // Plain TCP connection
        let (ws_stream, _response) = tokio_tungstenite::client_async(request, tcp_conn).await?;
        forward_ws_stdio(ws_stream, stdin(), stdout()).await
    }
}

#[derive(Debug)]
struct ProxyClientInner {
    listen_addr: SocketAddr,
    server_url: String,
    tls_options: TlsOptions,
}

/// A proxy client that forwards TCP connections through WebSocket.
///
/// # Example
///
/// ```no_run
/// use wsproxy::ProxyClient;
///
/// # async fn example() -> wsproxy::Result<()> {
/// let client = ProxyClient::bind(
///     "127.0.0.1:2222",
///     "ws://proxy-server:8080/ssh",
///     Default::default(),
/// )?;
///
/// client.run().await?;
/// # Ok(())
/// # }
/// ```
pub struct ProxyClient {
    bindable: Bindable,
    inner: Arc<ProxyClientInner>,
}

impl ProxyClient {
    /// Create a new proxy client.
    ///
    /// # Arguments
    ///
    /// * `bindable` - The address to listen on, or a pre-bound `TcpListener`.
    /// * `server_url` - The WebSocket server URL to connect to (e.g., "ws://127.0.0.1:8080/ssh").
    /// * `tls_options` - TLS options for certificate verification.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use tokio::net::TcpListener;
    /// use wsproxy::ProxyClient;
    ///
    /// # async fn example() -> wsproxy::Result<()> {
    /// // Bind to a specific address
    /// let client = ProxyClient::bind(
    ///     "127.0.0.1:2222",
    ///     "ws://proxy-server:8080/ssh",
    ///     Default::default(),
    /// )?;
    ///
    /// // Or use a pre-bound listener (useful for port 0)
    /// let listener = TcpListener::bind("127.0.0.1:0").await?;
    /// let port = listener.local_addr()?.port();
    /// let client = ProxyClient::bind(
    ///     listener,
    ///     "ws://proxy-server:8080/ssh",
    ///     Default::default(),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn bind(
        bindable: impl IntoBindable,
        server_url: impl Into<String>,
        tls_options: TlsOptions,
    ) -> Result<Self> {
        let bindable = bindable.into_bindable()?;
        let listen_addr = bindable.local_addr()?;

        Ok(Self {
            bindable,
            inner: Arc::new(ProxyClientInner {
                listen_addr,
                server_url: server_url.into(),
                tls_options,
            }),
        })
    }

    /// Get the configured listen address.
    pub fn local_addr(&self) -> SocketAddr {
        self.inner.listen_addr
    }

    /// Run the proxy client.
    ///
    /// This will listen for TCP connections and forward data through WebSocket to the server.
    /// If the client was created with a pre-bound `TcpListener` (via `bind(listener, ...)`),
    /// that listener will be used directly.
    pub async fn run(self) -> Result<()> {
        let listener = match self.bindable {
            Bindable::Address(addr) => TcpListener::bind(addr).await?,
            Bindable::Listener(l) => l,
        };

        loop {
            let (stream, peer_addr) = listener.accept().await?;
            let server_url = self.inner.server_url.clone();
            let tls_options = self.inner.tls_options.clone();

            tokio::spawn(async move {
                if let Err(e) = handle_tcp_connection(stream, &server_url, &tls_options).await {
                    eprintln!("Error handling connection from {}: {}", peer_addr, e);
                }
            });
        }
    }
}

async fn handle_tcp_connection(
    tcp_stream: TcpStream,
    server_url: &str,
    tls_options: &TlsOptions,
) -> Result<()> {
    // Connect to WebSocket server (supports both ws:// and wss://)
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;

    let request = server_url.into_client_request()?;
    let uri = request.uri();
    let scheme = uri.scheme_str().unwrap_or("ws");
    let host = uri
        .host()
        .ok_or_else(|| Error::config("missing host in URL"))?;
    let port = uri
        .port_u16()
        .unwrap_or(if scheme == "wss" { 443 } else { 80 });

    let addr = format!("{}:{}", host, port);
    let tcp_conn = TcpStream::connect(&addr).await?;

    if scheme == "wss" {
        // TLS connection
        use tokio_rustls::rustls::pki_types::ServerName;

        let config = build_tls_config(tls_options)?;

        let connector = tokio_rustls::TlsConnector::from(Arc::new(config));
        let server_name = ServerName::try_from(host.to_string())
            .map_err(|e| Error::config(format!("invalid server name: {}", e)))?;

        let tls_stream = connector.connect(server_name, tcp_conn).await?;
        let (ws_stream, _response) = tokio_tungstenite::client_async(request, tls_stream).await?;
        forward_ws_tcp(ws_stream, tcp_stream).await
    } else {
        // Plain TCP connection
        let (ws_stream, _response) = tokio_tungstenite::client_async(request, tcp_conn).await?;
        forward_ws_tcp(ws_stream, tcp_stream).await
    }
}

/// Build TLS client configuration based on options
fn build_tls_config(tls_options: &TlsOptions) -> Result<tokio_rustls::rustls::ClientConfig> {
    use tokio_rustls::rustls::client::danger::{
        HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,
    };
    use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName, UnixTime};
    use tokio_rustls::rustls::{DigitallySignedStruct, SignatureScheme};

    if tls_options.insecure {
        // Skip certificate verification (dangerous!)
        #[derive(Debug)]
        struct InsecureVerifier;

        impl ServerCertVerifier for InsecureVerifier {
            fn verify_server_cert(
                &self,
                _end_entity: &CertificateDer<'_>,
                _intermediates: &[CertificateDer<'_>],
                _server_name: &ServerName<'_>,
                _ocsp_response: &[u8],
                _now: UnixTime,
            ) -> std::result::Result<ServerCertVerified, tokio_rustls::rustls::Error> {
                Ok(ServerCertVerified::assertion())
            }

            fn verify_tls12_signature(
                &self,
                _message: &[u8],
                _cert: &CertificateDer<'_>,
                _dss: &DigitallySignedStruct,
            ) -> std::result::Result<HandshakeSignatureValid, tokio_rustls::rustls::Error>
            {
                Ok(HandshakeSignatureValid::assertion())
            }

            fn verify_tls13_signature(
                &self,
                _message: &[u8],
                _cert: &CertificateDer<'_>,
                _dss: &DigitallySignedStruct,
            ) -> std::result::Result<HandshakeSignatureValid, tokio_rustls::rustls::Error>
            {
                Ok(HandshakeSignatureValid::assertion())
            }

            fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
                vec![
                    SignatureScheme::RSA_PKCS1_SHA256,
                    SignatureScheme::RSA_PKCS1_SHA384,
                    SignatureScheme::RSA_PKCS1_SHA512,
                    SignatureScheme::ECDSA_NISTP256_SHA256,
                    SignatureScheme::ECDSA_NISTP384_SHA384,
                    SignatureScheme::ECDSA_NISTP521_SHA512,
                    SignatureScheme::RSA_PSS_SHA256,
                    SignatureScheme::RSA_PSS_SHA384,
                    SignatureScheme::RSA_PSS_SHA512,
                    SignatureScheme::ED25519,
                ]
            }
        }

        let config = tokio_rustls::rustls::ClientConfig::builder()
            .dangerous()
            .with_custom_certificate_verifier(Arc::new(InsecureVerifier))
            .with_no_client_auth();

        Ok(config)
    } else if let Some(ca_cert_path) = &tls_options.ca_cert_path {
        // Use custom CA certificate
        use std::io::BufReader;

        let ca_file = std::fs::File::open(ca_cert_path).map_err(|e| {
            Error::config(format!(
                "failed to open CA certificate '{}': {}",
                ca_cert_path, e
            ))
        })?;

        let certs: Vec<_> = rustls_pemfile::certs(&mut BufReader::new(ca_file))
            .collect::<std::result::Result<_, _>>()
            .map_err(|e| Error::config(format!("failed to parse CA certificate: {}", e)))?;

        let mut root_store = tokio_rustls::rustls::RootCertStore::empty();
        for cert in certs {
            root_store.add(cert).map_err(|e| {
                Error::config(format!("failed to add CA certificate to root store: {}", e))
            })?;
        }

        let config = tokio_rustls::rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        Ok(config)
    } else {
        // Use system root certificates
        let mut root_store = tokio_rustls::rustls::RootCertStore::empty();
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

        let config = tokio_rustls::rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        Ok(config)
    }
}

async fn forward_ws_tcp<S>(
    ws_stream: tokio_tungstenite::WebSocketStream<S>,
    tcp_stream: TcpStream,
) -> Result<()>
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
    let (mut ws_write, mut ws_read) = ws_stream.split();

    // Split TCP stream
    let (mut tcp_read, mut tcp_write) = tcp_stream.into_split();

    // Forward TCP -> WebSocket
    let tcp_to_ws = async {
        let mut buf = vec![0u8; 8192];
        loop {
            let n = tcp_read.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            ws_write
                .send(Message::Binary(buf[..n].to_vec().into()))
                .await?;
        }
        Ok::<_, Error>(())
    };

    // Forward WebSocket -> TCP
    let ws_to_tcp = async {
        while let Some(msg) = ws_read.next().await {
            match msg {
                Ok(Message::Binary(data)) => {
                    tcp_write.write_all(&data).await?;
                }
                Ok(Message::Text(text)) => {
                    tcp_write.write_all(text.as_bytes()).await?;
                }
                Ok(Message::Close(_)) => {
                    break;
                }
                Ok(Message::Ping(_)) | Ok(Message::Pong(_)) | Ok(Message::Frame(_)) => {
                    // Handled by the library or ignored
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
        Ok::<_, Error>(())
    };

    // Run both directions concurrently
    tokio::select! {
        result = tcp_to_ws => result?,
        result = ws_to_tcp => result?,
    }

    Ok(())
}

async fn forward_ws_stdio<S, R, W>(
    ws_stream: tokio_tungstenite::WebSocketStream<S>,
    mut stdin: R,
    mut stdout: W,
) -> Result<()>
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
    R: tokio::io::AsyncRead + Unpin,
    W: tokio::io::AsyncWrite + Unpin,
{
    let (mut ws_write, mut ws_read) = ws_stream.split();

    // Forward stdin -> WebSocket
    let stdin_to_ws = async {
        let mut buf = vec![0u8; 8192];
        loop {
            let n = stdin.read(&mut buf).await?;
            if n == 0 {
                // stdin closed, send close frame
                let _ = ws_write.send(Message::Close(None)).await;
                break;
            }
            ws_write
                .send(Message::Binary(buf[..n].to_vec().into()))
                .await?;
        }
        Ok::<_, Error>(())
    };

    // Forward WebSocket -> stdout
    let ws_to_stdout = async {
        while let Some(msg) = ws_read.next().await {
            match msg {
                Ok(Message::Binary(data)) => {
                    stdout.write_all(&data).await?;
                    stdout.flush().await?;
                }
                Ok(Message::Text(text)) => {
                    stdout.write_all(text.as_bytes()).await?;
                    stdout.flush().await?;
                }
                Ok(Message::Close(_)) => {
                    break;
                }
                Ok(Message::Ping(_)) | Ok(Message::Pong(_)) | Ok(Message::Frame(_)) => {
                    // Handled by the library or ignored
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
        Ok::<_, Error>(())
    };

    // Run both directions concurrently
    tokio::select! {
        result = stdin_to_ws => result?,
        result = ws_to_stdout => result?,
    }

    Ok(())
}