rama-socks5 0.4.0

SOCKS5 support for rama
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use std::time::Duration;

use rama_core::{
    Service, combinators::Either, error::BoxError, extensions::ExtensionsRef, io::Io,
    layer::timeout::DefaultTimeout, telemetry::tracing,
};
use rama_net::{
    address::{HostWithPort, SocketAddress},
    socket::SocketService,
    stream::SocketInfo,
};
use rama_udp::{UdpSocket, bind_udp_with_address};
use rama_utils::macros::generate_set_and_with;

#[cfg(feature = "dns")]
use ::rama_dns::client::resolver::{BoxDnsAddressResolver, DnsAddressResolver};

use super::Error;
use crate::proto::{ReplyKind, server::Reply};

mod inspect;
use inspect::UdpPacketProxy;
pub use inspect::{
    AsyncUdpInspector, DirectUdpRelay, RelayDirection, RelayRequest, RelayResponse,
    SyncUdpInspector, UdpInspectAction, UdpInspector,
};

mod relay;
pub use relay::UnspecifiedClientUdpAddressPolicy;

#[cfg(feature = "dns")]
type MaybeDnsResolver = Option<BoxDnsAddressResolver>;

/// Types which can be used as socks5 [`Command::UdpAssociate`] drivers on the server side.
///
/// Typically used as a component part of a [`Socks5Acceptor`].
///
/// The actual underlying trait is sealed and not exposed for usage.
/// No custom associators can be implemented. You can however customise
/// the individual steps as provided and used by [`UdpRelay`].
///
/// [`Socks5Acceptor`]: crate::server::Socks5Acceptor
/// [`Command::UdpAssociate`]: crate::proto::Command::UdpAssociate
pub trait Socks5UdpAssociator<S>: Socks5UdpAssociatorSeal<S> {}

impl<S, C> Socks5UdpAssociator<S> for C where C: Socks5UdpAssociatorSeal<S> {}

pub trait Socks5UdpAssociatorSeal<S>: Send + Sync + 'static {
    fn accept_udp_associate(
        &self,
        stream: S,
        destination: HostWithPort,
    ) -> impl Future<Output = Result<(), Error>> + Send + '_
    where
        S: Io + Unpin;
}

impl<S> Socks5UdpAssociatorSeal<S> for ()
where
    S: Io + Unpin,
{
    async fn accept_udp_associate(
        &self,

        mut stream: S,
        destination: HostWithPort,
    ) -> Result<(), Error> {
        tracing::debug!(
            "socks5 server w/ destination {destination}: abort: command not supported: UDP Associate",
        );

        Reply::error_reply(ReplyKind::CommandNotSupported)
            .write_to(&mut stream)
            .await
            .map_err(|err| {
                Error::io(err)
                    .with_context("write server reply: command not supported (udp associate)")
            })?;
        Err(Error::aborted("command not supported: UDP Associate"))
    }
}

#[derive(Debug, Clone, Default)]
#[non_exhaustive]
/// [`Default`] binder [`Service`] implementation.
pub struct DefaultUdpBinder;

impl Service<SocketAddress> for DefaultUdpBinder {
    type Output = UdpSocket;
    type Error = BoxError;

    async fn serve(&self, addr: SocketAddress) -> Result<Self::Output, Self::Error> {
        let socket = bind_udp_with_address(addr).await?;
        Ok(socket)
    }
}

/// Default binder [`Service`] type.
pub type DefaultUdpRelay = UdpRelay<DefaultTimeout<DefaultUdpBinder>, DirectUdpRelay>;

/// Only "useful" public [`Socks5UdpAssociator`] implementation,
/// which actually is able to accept udp-relay requests and process them.
///
/// The [`Default`] implementation opens a new (udp) socket for accepting 1
/// incoming connection. Once received it will relay incoming packets
/// to the target udp socket and relay received packets from the latter
/// back to the socks5 server cient. Prefixing these upd packets
/// using [`UdpHeader`][crate::proto::udp::UdpHeader].
///
/// You can customise the [`UdpRelay`] fully by creating it using [`UdpRelay::new`]
/// or overwrite any of the default components using [`UdpRelay::with_binder`],
/// [`UdpRelay::with_sync_inspector`] and [`UdpRelay::with_async_inspector`].
#[derive(Debug, Clone)]
pub struct UdpRelay<B, I> {
    binder: B,
    inspector: I,

    #[cfg(feature = "dns")]
    dns_resolver: MaybeDnsResolver,

    bind_north_address: SocketAddress,
    bind_south_address: SocketAddress,

    north_buffer_size: usize,
    south_buffer_size: usize,

    relay_timeout: Option<Duration>,

    unspecified_client_udp_address_policy: UnspecifiedClientUdpAddressPolicy,
}

impl<B> UdpRelay<B, DirectUdpRelay> {
    /// Create a new [`UdpRelay`].
    pub fn new(binder: B) -> Self {
        Self {
            binder,
            inspector: DirectUdpRelay::default(),
            #[cfg(feature = "dns")]
            dns_resolver: Default::default(),
            bind_north_address: SocketAddress::default_ipv4(0),
            bind_south_address: SocketAddress::default_ipv4(0),
            north_buffer_size: 4096,
            south_buffer_size: 4096,
            relay_timeout: None,
            unspecified_client_udp_address_policy: UnspecifiedClientUdpAddressPolicy::default(),
        }
    }

    /// Overwrite the [`UdpRelay`]'s [`SyncUdpInspector`] [`UdpInspector`]
    /// that can be used to inspect / modify a udp packet to be relayed synchronously.
    pub fn with_sync_inspector<T>(self, inspector: T) -> UdpRelay<B, SyncUdpInspector<T>> {
        UdpRelay {
            binder: self.binder,
            inspector: SyncUdpInspector(inspector),
            #[cfg(feature = "dns")]
            dns_resolver: self.dns_resolver,
            bind_north_address: self.bind_north_address,
            bind_south_address: self.bind_south_address,
            north_buffer_size: self.north_buffer_size,
            south_buffer_size: self.south_buffer_size,
            relay_timeout: self.relay_timeout,
            unspecified_client_udp_address_policy: self.unspecified_client_udp_address_policy,
        }
    }

    /// Overwrite the [`UdpRelay`]'s [`AsyncUdpInspector`] [`Service`]
    /// that can be used to inspect / modify a udp packet to be relayed asynchronously.
    pub fn with_async_inspector<T>(self, inspector: T) -> UdpRelay<B, AsyncUdpInspector<T>> {
        UdpRelay {
            binder: self.binder,
            inspector: AsyncUdpInspector(inspector),
            #[cfg(feature = "dns")]
            dns_resolver: self.dns_resolver,
            bind_north_address: self.bind_north_address,
            bind_south_address: self.bind_south_address,
            north_buffer_size: self.north_buffer_size,
            south_buffer_size: self.south_buffer_size,
            relay_timeout: self.relay_timeout,
            unspecified_client_udp_address_policy: self.unspecified_client_udp_address_policy,
        }
    }
}

impl<B, I> UdpRelay<B, I> {
    /// Overwrite the [`UdpRelay`]'s bind [`SocketService`],
    /// used to open a socket, return the address and
    /// wait for an incoming connection which it will return.
    pub fn with_binder<T>(self, binder: T) -> UdpRelay<T, I> {
        UdpRelay {
            binder,
            inspector: self.inspector,
            #[cfg(feature = "dns")]
            dns_resolver: self.dns_resolver,
            bind_north_address: self.bind_north_address,
            bind_south_address: self.bind_south_address,
            north_buffer_size: self.north_buffer_size,
            south_buffer_size: self.south_buffer_size,
            relay_timeout: self.relay_timeout,
            unspecified_client_udp_address_policy: self.unspecified_client_udp_address_policy,
        }
    }

    generate_set_and_with! {
        /// Define the [`SocketAddress`] to bind to, for both north and south direction.
        ///
        /// By default it binds the udp sockets at `0.0.0.0:0`.
        pub fn bind_address(mut self, address: impl Into<SocketAddress>) -> Self {
            let address = address.into();
            self.bind_north_address = address;
            self.bind_south_address = address;
            self
        }
    }

    generate_set_and_with! {
        /// Define the [`SocketAddress`] to bind to, for the north direction.
        ///
        /// By default it binds the udp sockets at `0.0.0.0:0`.
        pub fn bind_north_address(mut self, address: impl Into<SocketAddress>) -> Self {
            self.bind_north_address = address.into();
            self
        }
    }

    generate_set_and_with! {
        /// Define the [`SocketAddress`] to bind to, for the south direction.
        ///
        /// By default it binds the udp sockets at `0.0.0.0:0`.
        pub fn bind_south_address(mut self, address: impl Into<SocketAddress>) -> Self {
            self.bind_south_address = address.into();
            self
        }
    }

    generate_set_and_with! {
        /// Set the size of the buffer used to read south traffic.
        pub fn buffer_size_south(mut self, n: usize) -> Self {
            self.south_buffer_size = n;
            self
        }
    }

    generate_set_and_with! {
        /// Set the size of the buffer used to read north traffic.
        pub fn buffer_size_north(mut self, n: usize) -> Self {
            self.north_buffer_size = n;
            self
        }
    }

    generate_set_and_with! {
        /// Set the size of the buffer used to read both north and south traffic.
        pub fn buffer_size(mut self, n: usize) -> Self {
            self.north_buffer_size = n;
            self.south_buffer_size = n;
            self
        }
    }

    generate_set_and_with! {
        /// Define the relay timeout for this socks5 UDP server.
        pub fn relay_timeout(mut self, timeout: Option<Duration>) -> Self {
            self.relay_timeout = timeout;
            self
        }
    }

    generate_set_and_with! {
        /// Set how a UDP ASSOCIATE relay handles an all-zero client UDP address.
        ///
        /// Defaults to [`UnspecifiedClientUdpAddressPolicy::PinToTcpPeerIp`].
        pub fn unspecified_client_udp_address_policy(
            mut self,
            policy: UnspecifiedClientUdpAddressPolicy,
        ) -> Self {
            self.unspecified_client_udp_address_policy = policy;
            self
        }
    }
}

#[cfg(feature = "dns")]
impl<B, I> UdpRelay<B, I> {
    generate_set_and_with! {
        /// Attach the default [`DnsAddressResolver`] to this [`UdpRelay`].
        ///
        /// It will be used to best-effort resolve the domain name,
        /// in case a domain name is passed to forward to the target server.
        pub fn default_dns_resolver(mut self) -> Self {
            self.dns_resolver = Some(::rama_dns::client::GlobalDnsResolver::new().into_box_dns_address_resolver());
            self
        }
    }

    generate_set_and_with! {
        /// Attach a [`DnsAddressResolver`] to this [`UdpRelay`].
        ///
        /// It will be used to best-effort resolve the domain name,
        /// in case a domain name is passed to forward to the target server.
        pub fn dns_resolver(mut self, resolver: Option<BoxDnsAddressResolver>) -> Self {
            self.dns_resolver = resolver;
            self
        }
    }

    /// Attach a [`DnsAddressResolver`] to this [`UdpRelay`].
    ///
    /// It will be used to best-effort resolve the domain name,
    /// in case a domain name is passed to forward to the target server.
    #[must_use]
    pub fn with_dns_address_resolver(mut self, resolver: impl DnsAddressResolver) -> Self {
        self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
        self
    }

    /// Attach a [`DnsAddressResolver`] to this [`UdpRelay`].
    ///
    /// It will be used to best-effort resolve the domain name,
    /// in case a domain name is passed to forward to the target server.
    pub fn set_dns_address_resolver(&mut self, resolver: impl DnsAddressResolver) -> &mut Self {
        self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
        self
    }
}

impl Default for DefaultUdpRelay {
    fn default() -> Self {
        let relay = Self::new(DefaultTimeout::new(
            DefaultUdpBinder::default(),
            Duration::from_secs(30),
        ))
        .with_relay_timeout(Duration::from_secs(300));
        #[cfg(feature = "dns")]
        let relay = relay.with_default_dns_resolver();
        relay
    }
}

impl<B, I, S> Socks5UdpAssociatorSeal<S> for UdpRelay<B, I>
where
    B: SocketService<Socket = UdpSocket>,
    I: UdpPacketProxy,
    S: Io + Unpin + ExtensionsRef,
{
    async fn accept_udp_associate(
        &self,
        mut stream: S,
        destination: HostWithPort,
    ) -> Result<(), Error> {
        tracing::trace!(
            "socks5 server w/ destination {destination}: udp associate: try to bind incoming socket to destination {destination}",
        );

        let extensions = stream.extensions().clone();

        let HostWithPort {
            host: dest_host,
            port: dest_port,
        } = destination;

        // UDP-associate bind address MUST be an IP. `try_as_ip` bridges
        // pct-encoded IPv4 inside `Uninterpreted`; anything else fails.
        let Ok(dest_addr) = dest_host.try_as_ip() else {
            tracing::debug!(
                "udp associate command does not accept non-IP host {dest_host} as bind address",
            );
            let reply_kind = ReplyKind::AddressTypeNotSupported;
            Reply::error_reply(reply_kind)
                .write_to(&mut stream)
                .await
                .map_err(|err| {
                    Error::io(err).with_context("write server reply: udp relay failed")
                })?;
            return Err(Error::aborted("udp relay failed").with_context(reply_kind));
        };
        let client_address = SocketAddress::new(dest_addr, dest_port);
        let tcp_peer_ip = extensions
            .get_ref::<SocketInfo>()
            .map(|info| info.peer_addr().ip_addr);

        if client_address.ip_addr.is_unspecified()
            && self.unspecified_client_udp_address_policy
                == UnspecifiedClientUdpAddressPolicy::PinToTcpPeerIp
            && tcp_peer_ip.is_none()
        {
            tracing::warn!(
                "socks5 udp associate: PinToTcpPeerIp cannot enforce IP filtering \
                 (no SocketInfo / TCP peer IP available); degrading to first-packet pinning",
            );
        }

        let socket_north = match self
            .binder
            .bind_socket_with_address(self.bind_north_address)
            .await
        {
            Ok(twin) => twin,
            Err(err) => {
                let err = err.into();

                tracing::debug!("udp north socket bind failed: {err:?}",);

                let reply_kind = ReplyKind::GeneralServerFailure;
                Reply::error_reply(reply_kind)
                    .write_to(&mut stream)
                    .await
                    .map_err(|err| {
                        Error::io(err)
                            .with_context("write server reply: udp north socket bind failed")
                    })?;
                return Err(Error::aborted("udp north socket bind failed")
                    .with_context(reply_kind)
                    .with_source(err));
            }
        };

        let socket_north_address = match socket_north.local_addr() {
            Ok(addr) => addr,
            Err(err) => {
                tracing::debug!("retrieve local addr of north (udp) socket failed: {err:?}");
                let reply_kind = ReplyKind::GeneralServerFailure;
                Reply::error_reply(reply_kind)
                    .write_to(&mut stream)
                    .await
                    .map_err(|err| {
                        Error::io(err)
                            .with_context("write server reply: prepare udp receive socket failed")
                    })?;
                return Err(
                    Error::aborted("prepare udp receive socket failed").with_context(reply_kind)
                );
            }
        };

        let socket_south = match self
            .binder
            .bind_socket_with_address(self.bind_south_address)
            .await
        {
            Ok(twin) => twin,
            Err(err) => {
                let err = err.into();

                tracing::debug!("udp south socket bind failed: {err:?}",);

                let reply_kind = ReplyKind::GeneralServerFailure;
                Reply::error_reply(reply_kind)
                    .write_to(&mut stream)
                    .await
                    .map_err(|err| {
                        Error::io(err)
                            .with_context("write server reply: udp south socket bind failed")
                    })?;
                return Err(Error::aborted("udp south socket bind failed")
                    .with_context(reply_kind)
                    .with_source(err));
            }
        };

        Reply::new(socket_north_address)
            .write_to(&mut stream)
            .await
            .map_err(|err| {
                Error::io(err)
                    .with_context("write server reply: udp associate: north+south sockets ready")
            })?;

        let mut empty = tokio::io::empty();
        let mut drop_stream_fut = std::pin::pin!(tokio::io::copy(&mut stream, &mut empty));
        let mut timeout_fut = std::pin::pin!(match self.relay_timeout {
            Some(timeout) => Either::A(tokio::time::sleep(timeout)),
            None => Either::B(std::future::pending::<()>()),
        });

        #[cfg(feature = "dns")]
        let udp_relay = self.inspector.proxy_udp_packets(
            extensions,
            client_address,
            socket_north,
            self.north_buffer_size,
            socket_south,
            self.south_buffer_size,
            self.dns_resolver.clone(),
            self.unspecified_client_udp_address_policy,
            tcp_peer_ip,
        );

        #[cfg(not(feature = "dns"))]
        let udp_relay = self.inspector.proxy_udp_packets(
            extensions,
            client_address,
            socket_north,
            self.north_buffer_size,
            socket_south,
            self.south_buffer_size,
            self.unspecified_client_udp_address_policy,
            tcp_peer_ip,
        );

        tokio::select! {
            _ = &mut drop_stream_fut => {
                tracing::trace!(
                    network.peer.address = %client_address.ip_addr,
                    network.peer.port = %client_address.port,
                    "socks5 server: udp associate: tcp stream dropped from client: drop relay",
                );
            }

            _ = &mut timeout_fut => {
                tracing::debug!(
                    network.peer.address = %client_address.ip_addr,
                    network.peer.port = %client_address.port,
                    "socks5 server: udp associate: timeout reached: drop relay",
                );
                return Err(Error::io(std::io::Error::new(std::io::ErrorKind::TimedOut, "relay timeout reached")));
            }

            Err(err) = udp_relay => {
                tracing::debug!(
                    network.peer.address = %client_address.ip_addr,
                    network.peer.port = %client_address.port,
                    "socks5 server: udp associate: udp relay: exit with an error",
                );
                return Err(err);
            }
        }

        tracing::trace!(
            network.peer.address = %client_address.ip_addr,
            network.peer.port = %client_address.port,
            "socks5 server: udp associate: udp relay: done",);
        Ok(())
    }
}

#[cfg(test)]
pub(crate) use test::MockUdpAssociator;

#[cfg(test)]
mod test;