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
//! Fast SOCKS5 client/server implementation written in Rust async/.await (with tokio).
//!
//! This library is maintained by [anyip.io](https://anyip.io/) a residential and mobile socks5 proxy provider.
//!
//! ## Features
//!
//! - An `async`/`.await` [SOCKS5](https://tools.ietf.org/html/rfc1928) implementation.
//! - An `async`/`.await` [SOCKS4 Client](https://www.openssh.com/txt/socks4.protocol) implementation.
//! - An `async`/`.await` [SOCKS4a Client](https://www.openssh.com/txt/socks4a.protocol) implementation.
//! - No **unsafe** code
//! - Built on-top of `tokio` library
//! - Ultra lightweight and scalable
//! - No system dependencies
//! - Cross-platform
//! - Authentication methods:
//!   - No-Auth method
//!   - Username/Password auth method
//!   - Custom auth methods can be implemented via the Authentication Trait
//!   - Credentials returned on authentication success
//! - All SOCKS5 RFC errors (replies) should be mapped
//! - `AsyncRead + AsyncWrite` traits are implemented on Socks5Stream & Socks5Socket
//! - `IPv4`, `IPv6`, and `Domains` types are supported
//! - Config helper for Socks5Server
//! - Helpers to run a Socks5Server à la *"std's TcpStream"* via `incoming.next().await`
//! - Examples come with real cases commands scenarios
//! - Can disable `DNS resolving`
//! - Can skip the authentication/handshake process, which will directly handle command's request (useful to save useless round-trips in a current authenticated environment)
//! - Can disable command execution (useful if you just want to forward the request to a different server)
//!
//!
//! ## Install
//!
//! Open in [crates.io](https://crates.io/crates/fast-socks5).
//!
//!
//! ## Examples
//!
//! Please check [`examples`](https://github.com/dizda/fast-socks5/tree/master/examples) directory.

#![forbid(unsafe_code)]
#[macro_use]
extern crate log;

pub mod client;
pub mod server;
pub mod util;

#[cfg(feature = "socks4")]
pub mod socks4;

use anyhow::Context;
use std::fmt;
use std::io;
use thiserror::Error;
use util::target_addr::read_address;
use util::target_addr::TargetAddr;
use util::target_addr::ToTargetAddr;

use tokio::io::AsyncReadExt;

#[rustfmt::skip]
pub mod consts {
    pub const SOCKS5_VERSION:                          u8 = 0x05;

    pub const SOCKS5_AUTH_METHOD_NONE:                 u8 = 0x00;
    pub const SOCKS5_AUTH_METHOD_GSSAPI:               u8 = 0x01;
    pub const SOCKS5_AUTH_METHOD_PASSWORD:             u8 = 0x02;
    pub const SOCKS5_AUTH_METHOD_NOT_ACCEPTABLE:       u8 = 0xff;

    pub const SOCKS5_CMD_TCP_CONNECT:                  u8 = 0x01;
    pub const SOCKS5_CMD_TCP_BIND:                     u8 = 0x02;
    pub const SOCKS5_CMD_UDP_ASSOCIATE:                u8 = 0x03;

    pub const SOCKS5_ADDR_TYPE_IPV4:                   u8 = 0x01;
    pub const SOCKS5_ADDR_TYPE_DOMAIN_NAME:            u8 = 0x03;
    pub const SOCKS5_ADDR_TYPE_IPV6:                   u8 = 0x04;

    pub const SOCKS5_REPLY_SUCCEEDED:                  u8 = 0x00;
    pub const SOCKS5_REPLY_GENERAL_FAILURE:            u8 = 0x01;
    pub const SOCKS5_REPLY_CONNECTION_NOT_ALLOWED:     u8 = 0x02;
    pub const SOCKS5_REPLY_NETWORK_UNREACHABLE:        u8 = 0x03;
    pub const SOCKS5_REPLY_HOST_UNREACHABLE:           u8 = 0x04;
    pub const SOCKS5_REPLY_CONNECTION_REFUSED:         u8 = 0x05;
    pub const SOCKS5_REPLY_TTL_EXPIRED:                u8 = 0x06;
    pub const SOCKS5_REPLY_COMMAND_NOT_SUPPORTED:      u8 = 0x07;
    pub const SOCKS5_REPLY_ADDRESS_TYPE_NOT_SUPPORTED: u8 = 0x08;
}

#[derive(Debug, PartialEq)]
pub enum Socks5Command {
    TCPConnect,
    TCPBind,
    UDPAssociate,
}

#[allow(dead_code)]
impl Socks5Command {
    #[inline]
    #[rustfmt::skip]
    fn as_u8(&self) -> u8 {
        match self {
            Socks5Command::TCPConnect   => consts::SOCKS5_CMD_TCP_CONNECT,
            Socks5Command::TCPBind      => consts::SOCKS5_CMD_TCP_BIND,
            Socks5Command::UDPAssociate => consts::SOCKS5_CMD_UDP_ASSOCIATE,
        }
    }

    #[inline]
    #[rustfmt::skip]
    fn from_u8(code: u8) -> Option<Socks5Command> {
        match code {
            consts::SOCKS5_CMD_TCP_CONNECT      => Some(Socks5Command::TCPConnect),
            consts::SOCKS5_CMD_TCP_BIND         => Some(Socks5Command::TCPBind),
            consts::SOCKS5_CMD_UDP_ASSOCIATE    => Some(Socks5Command::UDPAssociate),
            _ => None,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum AuthenticationMethod {
    None,
    Password { username: String, password: String },
}

impl AuthenticationMethod {
    #[inline]
    #[rustfmt::skip]
    fn as_u8(&self) -> u8 {
        match self {
            AuthenticationMethod::None => consts::SOCKS5_AUTH_METHOD_NONE,
            AuthenticationMethod::Password {..} =>
                consts::SOCKS5_AUTH_METHOD_PASSWORD
        }
    }

    #[inline]
    #[rustfmt::skip]
    fn from_u8(code: u8) -> Option<AuthenticationMethod> {
        match code {
            consts::SOCKS5_AUTH_METHOD_NONE     => Some(AuthenticationMethod::None),
            consts::SOCKS5_AUTH_METHOD_PASSWORD => Some(AuthenticationMethod::Password { username: "test".to_string(), password: "test".to_string()}),
            _                                   => None,
        }
    }
}

impl fmt::Display for AuthenticationMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            AuthenticationMethod::None => f.write_str("AuthenticationMethod::None"),
            AuthenticationMethod::Password { .. } => f.write_str("AuthenticationMethod::Password"),
        }
    }
}

//impl Vec<AuthenticationMethod> {
//    pub fn as_bytes(&self) -> &[u8] {
//        self.iter().map(|l| l.as_u8()).collect()
//    }
//}
//
//impl From<&[AuthenticationMethod]> for &[u8] {
//    fn from(_: Vec<AuthenticationMethod>) -> Self {
//        &[0x00]
//    }
//}

#[derive(Error, Debug)]
pub enum SocksError {
    #[error("i/o error: {0}")]
    Io(#[from] io::Error),
    #[error("the data for key `{0}` is not available")]
    Redaction(String),
    #[error("invalid header (expected {expected:?}, found {found:?})")]
    InvalidHeader { expected: String, found: String },

    #[error("Auth method unacceptable `{0:?}`.")]
    AuthMethodUnacceptable(Vec<u8>),
    #[error("Unsupported SOCKS version `{0}`.")]
    UnsupportedSocksVersion(u8),
    #[error("Domain exceeded max sequence length")]
    ExceededMaxDomainLen(usize),
    #[error("Authentication failed `{0}`")]
    AuthenticationFailed(String),
    #[error("Authentication rejected `{0}`")]
    AuthenticationRejected(String),

    #[error("Error with reply: {0}.")]
    ReplyError(#[from] ReplyError),

    #[cfg(feature = "socks4")]
    #[error("Error with reply: {0}.")]
    ReplySocks4Error(#[from] socks4::ReplyError),

    #[error("Argument input error: `{0}`.")]
    ArgumentInputError(&'static str),

    //    #[error("Other: `{0}`.")]
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

pub type Result<T, E = SocksError> = core::result::Result<T, E>;

/// SOCKS5 reply code
#[derive(Error, Debug, Copy, Clone)]
pub enum ReplyError {
    #[error("Succeeded")]
    Succeeded,
    #[error("General failure")]
    GeneralFailure,
    #[error("Connection not allowed by ruleset")]
    ConnectionNotAllowed,
    #[error("Network unreachable")]
    NetworkUnreachable,
    #[error("Host unreachable")]
    HostUnreachable,
    #[error("Connection refused")]
    ConnectionRefused,
    #[error("Connection timeout")]
    ConnectionTimeout,
    #[error("TTL expired")]
    TtlExpired,
    #[error("Command not supported")]
    CommandNotSupported,
    #[error("Address type not supported")]
    AddressTypeNotSupported,
    //    OtherReply(u8),
}

impl ReplyError {
    #[inline]
    #[rustfmt::skip]
    pub fn as_u8(self) -> u8 {
        match self {
            ReplyError::Succeeded               => consts::SOCKS5_REPLY_SUCCEEDED,
            ReplyError::GeneralFailure          => consts::SOCKS5_REPLY_GENERAL_FAILURE,
            ReplyError::ConnectionNotAllowed    => consts::SOCKS5_REPLY_CONNECTION_NOT_ALLOWED,
            ReplyError::NetworkUnreachable      => consts::SOCKS5_REPLY_NETWORK_UNREACHABLE,
            ReplyError::HostUnreachable         => consts::SOCKS5_REPLY_HOST_UNREACHABLE,
            ReplyError::ConnectionRefused       => consts::SOCKS5_REPLY_CONNECTION_REFUSED,
            ReplyError::ConnectionTimeout       => consts::SOCKS5_REPLY_TTL_EXPIRED,
            ReplyError::TtlExpired              => consts::SOCKS5_REPLY_TTL_EXPIRED,
            ReplyError::CommandNotSupported     => consts::SOCKS5_REPLY_COMMAND_NOT_SUPPORTED,
            ReplyError::AddressTypeNotSupported => consts::SOCKS5_REPLY_ADDRESS_TYPE_NOT_SUPPORTED,
//            ReplyError::OtherReply(c)           => c,
        }
    }

    #[inline]
    #[rustfmt::skip]
    pub fn from_u8(code: u8) -> ReplyError {
        match code {
            consts::SOCKS5_REPLY_SUCCEEDED                  => ReplyError::Succeeded,
            consts::SOCKS5_REPLY_GENERAL_FAILURE            => ReplyError::GeneralFailure,
            consts::SOCKS5_REPLY_CONNECTION_NOT_ALLOWED     => ReplyError::ConnectionNotAllowed,
            consts::SOCKS5_REPLY_NETWORK_UNREACHABLE        => ReplyError::NetworkUnreachable,
            consts::SOCKS5_REPLY_HOST_UNREACHABLE           => ReplyError::HostUnreachable,
            consts::SOCKS5_REPLY_CONNECTION_REFUSED         => ReplyError::ConnectionRefused,
            consts::SOCKS5_REPLY_TTL_EXPIRED                => ReplyError::TtlExpired,
            consts::SOCKS5_REPLY_COMMAND_NOT_SUPPORTED      => ReplyError::CommandNotSupported,
            consts::SOCKS5_REPLY_ADDRESS_TYPE_NOT_SUPPORTED => ReplyError::AddressTypeNotSupported,
//            _                                               => ReplyError::OtherReply(code),
            _                                               => unreachable!("ReplyError code unsupported."),
        }
    }
}

/// Generate UDP header
///
/// # UDP Request header structure.
/// ```text
/// +----+------+------+----------+----------+----------+
/// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
/// +----+------+------+----------+----------+----------+
/// | 2  |  1   |  1   | Variable |    2     | Variable |
/// +----+------+------+----------+----------+----------+
///
/// The fields in the UDP request header are:
///
///     o  RSV  Reserved X'0000'
///     o  FRAG    Current fragment number
///     o  ATYP    address type of following addresses:
///        o  IP V4 address: X'01'
///        o  DOMAINNAME: X'03'
///        o  IP V6 address: X'04'
///     o  DST.ADDR       desired destination address
///     o  DST.PORT       desired destination port
///     o  DATA     user data
/// ```
pub fn new_udp_header<T: ToTargetAddr>(target_addr: T) -> Result<Vec<u8>> {
    let mut header = vec![
        0, 0, // RSV
        0, // FRAG
    ];
    header.append(&mut target_addr.to_target_addr()?.to_be_bytes()?);

    Ok(header)
}

/// Parse data from UDP client on raw buffer, return (frag, target_addr, payload).
pub async fn parse_udp_request<'a>(mut req: &'a [u8]) -> Result<(u8, TargetAddr, &'a [u8])> {
    let rsv = read_exact!(req, [0u8; 2]).context("Malformed request")?;

    if !rsv.eq(&[0u8; 2]) {
        return Err(ReplyError::GeneralFailure.into());
    }

    let [frag, atyp] = read_exact!(req, [0u8; 2]).context("Malformed request")?;

    let target_addr = read_address(&mut req, atyp).await.map_err(|e| {
        // print explicit error
        error!("{:#}", e);
        // then convert it to a reply
        ReplyError::AddressTypeNotSupported
    })?;

    Ok((frag, target_addr, req))
}

#[cfg(test)]
mod test {
    use anyhow::Result;
    use tokio::{
        net::{TcpListener, TcpStream, UdpSocket},
        sync::oneshot::Sender,
    };

    use crate::{
        client,
        server::{self, SimpleUserPassword},
    };
    use std::{
        net::{SocketAddr, ToSocketAddrs},
        num::ParseIntError,
        sync::Arc,
    };
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::oneshot;
    use tokio_test::block_on;

    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    async fn setup_socks_server(
        proxy_addr: &str,
        auth: Option<SimpleUserPassword>,
        tx: Sender<SocketAddr>,
    ) -> Result<()> {
        let mut config = server::Config::default();
        config.set_udp_support(true);
        let config = match auth {
            None => config,
            Some(up) => config.with_authentication(up),
        };

        let config = Arc::new(config);
        let listener = TcpListener::bind(proxy_addr).await?;
        tx.send(listener.local_addr()?).unwrap();
        loop {
            let (stream, _) = listener.accept().await?;
            let mut socks5_socket = server::Socks5Socket::new(stream, config.clone());
            socks5_socket.set_reply_ip(proxy_addr.parse::<SocketAddr>().unwrap().ip());

            socks5_socket.upgrade_to_socks5().await?;
        }
    }

    async fn google(mut socket: TcpStream) -> Result<()> {
        socket.write_all(b"GET / HTTP/1.0\r\n\r\n").await?;
        let mut result = vec![];
        socket.read_to_end(&mut result).await?;

        println!("{}", String::from_utf8_lossy(&result));
        assert!(result.starts_with(b"HTTP/1.0"));
        assert!(result.ends_with(b"</HTML>\r\n") || result.ends_with(b"</html>"));

        Ok(())
    }

    #[test]
    fn google_no_auth() {
        init();
        block_on(async {
            let (tx, rx) = oneshot::channel();
            tokio::spawn(setup_socks_server("[::1]:0", None, tx));

            let socket = client::Socks5Stream::connect(
                rx.await.unwrap(),
                "google.com".to_owned(),
                80,
                client::Config::default(),
            )
            .await
            .unwrap();
            google(socket.get_socket()).await.unwrap();
        });
    }

    #[test]
    fn mock_udp_assosiate_no_auth() {
        init();
        block_on(async {
            const MOCK_ADDRESS: &str = "[::1]:40235";

            let (tx, rx) = oneshot::channel();
            tokio::spawn(setup_socks_server("[::1]:0", None, tx));
            let backing_socket = TcpStream::connect(rx.await.unwrap()).await.unwrap();

            // Creates a UDP tunnel which can be used to forward UDP packets, "[::]:0" indicates the
            // binding source address used to communicate with the socks5 server.
            let tunnel = client::Socks5Datagram::bind(backing_socket, "[::]:0")
                .await
                .unwrap();
            let mock_udp_server = UdpSocket::bind(MOCK_ADDRESS).await.unwrap();

            tunnel
                .send_to(
                    b"hello world!",
                    MOCK_ADDRESS.to_socket_addrs().unwrap().next().unwrap(),
                )
                .await
                .unwrap();
            println!("Send packet to {}", MOCK_ADDRESS);

            let mut buf = [0; 13];
            let (len, addr) = mock_udp_server.recv_from(&mut buf).await.unwrap();
            assert_eq!(len, 12);
            assert_eq!(&buf[..12], b"hello world!");

            mock_udp_server
                .send_to(b"hello world!", addr)
                .await
                .unwrap();

            println!("Recieve packet from {}", MOCK_ADDRESS);
            let len = tunnel.recv_from(&mut buf).await.unwrap().0;
            assert_eq!(len, 12);
            assert_eq!(&buf[..12], b"hello world!");
        });
    }

    #[test]
    fn dns_udp_assosiate_no_auth() {
        init();
        block_on(async {
            const DNS_SERVER: &str = "1.1.1.1:53";

            let (tx, rx) = oneshot::channel();
            tokio::spawn(setup_socks_server("[::1]:0", None, tx));
            let backing_socket = TcpStream::connect(rx.await.unwrap()).await.unwrap();

            // Creates a UDP tunnel which can be used to forward UDP packets, "[::]:0" indicates the
            // binding source address used to communicate with the socks5 server.
            let tunnel = client::Socks5Datagram::bind(backing_socket, "[::]:0")
                .await
                .unwrap();

            #[rustfmt::skip]
            tunnel.send_to(
                &decode_hex(&(
                    "AAAA".to_owned()   // ID
                    + "0100"            // Query parameters
                    + "0001"            // Number of questions
                    + "0000"            // Number of answers
                    + "0000"            // Number of authority records
                    + "0000"            // Number of additional records
                    + "076578616d706c65"// Length + hex("example")
                    + "03636f6d00"      // Length + hex("com") + zero byte
                    + "0001"            // QTYPE
                    + "0001"            // QCLASS
                ))
                .unwrap(),
                DNS_SERVER.to_socket_addrs().unwrap().next().unwrap(),
            ).await.unwrap();
            println!("Send packet to {}", DNS_SERVER);

            let mut buf = [0; 128];
            println!("Recieve packet from {}", DNS_SERVER);
            tunnel.recv_from(&mut buf).await.unwrap();
            println!("dns response {:?}", buf);

            #[rustfmt::skip]
            assert!(buf.starts_with(&decode_hex(&(
                "AAAA".to_owned()   // ID
                + "8180"            // FLAGS: RCODE=0, No errors reported
                + "0001"            // One question
            )).unwrap()));
        });
    }

    fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
            .collect()
    }
}