alksocks 0.3.2

SOCKS5 (RFC 1928) proxy protocol over alkcall channels: targeted-forked fast-socks5 typestate core plus producer/consumer sessions. Producer/consumer protocol crate.
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
//! Forked from fast-socks5 v1.0.0 (upstream `src/util/target_addr.rs`;
//! extraction; ownership per ADR-013, see the crate root's
//! `mod.rs`).
//!
//! Upstream carries `TargetAddr`, the address codec (`read_address`),
//! and the `resolve_dns` helper; only the codec rode the extraction
//! (DNS resolution is the cut net region, since
//! `tokio::net::lookup_host`
//! is not in the wasm-clean graph). The `resolve_dns` method is cut
//! with its two `AddrError` variants (`DNSResolutionFailed`,
//! `NoDNSRecords`).

use crate::rfc1928::consts;
use crate::rfc1928::consts::SOCKS5_ADDR_TYPE_IPV4;
use crate::rfc1928::util::stream::read_exact;
use crate::rfc1928::ReplyError;
use std::fmt;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::vec::IntoIter;
use tokio::io::{AsyncRead, AsyncReadExt};

/// SOCKS5 reply code
#[derive(thiserror::Error, Debug)]
pub enum AddrError {
    #[error("Domain length {0} exceeded maximum")]
    DomainLenTooLong(usize),
    #[error("Can't read IPv4: {0}")]
    IPv4Unreadable(#[source] io::Error),
    #[error("Can't read IPv6: {0}")]
    IPv6Unreadable(#[source] io::Error),
    #[error("Can't read port number: {0}")]
    PortNumberUnreadable(#[source] io::Error),
    #[error("Can't read domain len: {0}")]
    DomainLenUnreadable(#[source] io::Error),
    #[error("Can't read domain content: {0}")]
    DomainContentUnreadable(#[source] io::Error),
    #[error("Can't convert address: {0}")]
    AddrConversionFailed(#[source] io::Error),
    #[error("Malformed UTF-8")]
    Utf8(#[source] std::string::FromUtf8Error),
    #[error("Unknown address type")]
    IncorrectAddressType,
}

impl AddrError {
    pub fn to_reply_error(&self) -> ReplyError {
        match self {
            AddrError::IncorrectAddressType => ReplyError::AddressTypeNotSupported,
            _ => ReplyError::ConnectionRefused,
        }
    }
}

/// A description of a connection target.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TargetAddr {
    /// Connect to an IP address.
    Ip(SocketAddr),
    /// Connect to a fully qualified domain name.
    ///
    /// The domain name will be passed along to the proxy server and DNS lookup
    /// will happen there.
    Domain(String, u16),
}

impl TargetAddr {
    pub fn is_ip(&self) -> bool {
        matches!(self, TargetAddr::Ip(_))
    }

    pub fn is_domain(&self) -> bool {
        !self.is_ip()
    }

    pub fn to_be_bytes(&self) -> Result<Vec<u8>, AddrError> {
        let mut buf = vec![];
        match self {
            TargetAddr::Ip(SocketAddr::V4(addr)) => {
                buf.extend_from_slice(&[SOCKS5_ADDR_TYPE_IPV4]);

                buf.extend_from_slice(&(addr.ip()).octets()); // ip
                buf.extend_from_slice(&addr.port().to_be_bytes()); // port
            }
            TargetAddr::Ip(SocketAddr::V6(addr)) => {
                buf.extend_from_slice(&[consts::SOCKS5_ADDR_TYPE_IPV6]);

                buf.extend_from_slice(&(addr.ip()).octets()); // ip
                buf.extend_from_slice(&addr.port().to_be_bytes()); // port
            }
            TargetAddr::Domain(ref domain, port) => {
                if domain.len() > u8::MAX as usize {
                    return Err(AddrError::DomainLenTooLong(domain.len()));
                }
                buf.extend_from_slice(&[consts::SOCKS5_ADDR_TYPE_DOMAIN_NAME, domain.len() as u8]);
                buf.extend_from_slice(domain.as_bytes()); // domain content
                buf.extend_from_slice(&port.to_be_bytes());
                // port content (.to_be_bytes() convert from u16 to u8 type)
            }
        }
        Ok(buf)
    }

    pub fn into_string_and_port(self) -> (String, u16) {
        match self {
            TargetAddr::Ip(socket_addr) => (socket_addr.ip().to_string(), socket_addr.port()),
            TargetAddr::Domain(domain, port) => (domain, port),
        }
    }
}

/// The blocking `ToSocketAddrs` form: IP targets resolve directly;
/// domain targets cannot be resolved here (domain resolution is the
/// egress's job, per ADR-012) and error.
impl std::net::ToSocketAddrs for TargetAddr {
    type Iter = IntoIter<SocketAddr>;

    fn to_socket_addrs(&self) -> io::Result<IntoIter<SocketAddr>> {
        match *self {
            TargetAddr::Ip(addr) => Ok(vec![addr].into_iter()),
            TargetAddr::Domain(_, _) => Err(io::Error::other(
                "Domain name cannot be resolved by the blocking ToSocketAddrs interface; resolve it before constructing the target.",
            )),
        }
    }
}

impl fmt::Display for TargetAddr {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TargetAddr::Ip(ref addr) => write!(f, "{}", addr),
            TargetAddr::Domain(ref addr, ref port) => write!(f, "{}:{}", addr, port),
        }
    }
}

/// A trait for objects that can be converted to `TargetAddr`.
pub trait ToTargetAddr {
    /// Converts the value of `self` to a `TargetAddr`.
    fn to_target_addr(&self) -> io::Result<TargetAddr>;
}

impl ToTargetAddr for (&str, u16) {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        // try to parse as an IP first
        if let Ok(addr) = self.0.parse::<Ipv4Addr>() {
            return (addr, self.1).to_target_addr();
        }

        if let Ok(addr) = self.0.parse::<Ipv6Addr>() {
            return (addr, self.1).to_target_addr();
        }

        Ok(TargetAddr::Domain(self.0.to_owned(), self.1))
    }
}

impl ToTargetAddr for SocketAddr {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        Ok(TargetAddr::Ip(*self))
    }
}

impl ToTargetAddr for SocketAddrV4 {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        SocketAddr::V4(*self).to_target_addr()
    }
}

impl ToTargetAddr for SocketAddrV6 {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        SocketAddr::V6(*self).to_target_addr()
    }
}

impl ToTargetAddr for (IpAddr, u16) {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        match self.0 {
            IpAddr::V4(ipv4_addr) => (ipv4_addr, self.1).to_target_addr(),
            IpAddr::V6(ipv6_addr) => (ipv6_addr, self.1).to_target_addr(),
        }
    }
}

impl ToTargetAddr for (Ipv4Addr, u16) {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        SocketAddrV4::new(self.0, self.1).to_target_addr()
    }
}

impl ToTargetAddr for (Ipv6Addr, u16) {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        SocketAddrV6::new(self.0, self.1, 0, 0).to_target_addr()
    }
}

impl ToTargetAddr for TargetAddr {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        Ok(self.clone())
    }
}

impl ToTargetAddr for &TargetAddr {
    fn to_target_addr(&self) -> io::Result<TargetAddr> {
        Ok((*self).clone())
    }
}

#[derive(Debug)]
pub enum Addr {
    V4([u8; 4]),
    V6([u8; 16]),
    // `String`, validated UTF-8 at the codec boundary (`read_address`
    // converts before constructing).
    Domain(String),
}

/// This function is used by the client & the server.
///
/// The domain arm's allocation is bounded by construction: the wire
/// length field is one byte, so the claimed length is at most 255;
/// the attacker-controlled byte cannot ask for more. Any change that
/// widens that field (an FRAG-style extension) requires an explicit
/// cap here before the allocation.
pub async fn read_address<T: AsyncRead + Unpin>(
    stream: &mut T,
    atyp: u8,
) -> Result<TargetAddr, AddrError> {
    let addr = match atyp {
        consts::SOCKS5_ADDR_TYPE_IPV4 => {
            Addr::V4(read_exact!(stream, [0u8; 4]).map_err(AddrError::IPv4Unreadable)?)
        }
        consts::SOCKS5_ADDR_TYPE_IPV6 => {
            Addr::V6(read_exact!(stream, [0u8; 16]).map_err(AddrError::IPv6Unreadable)?)
        }
        consts::SOCKS5_ADDR_TYPE_DOMAIN_NAME => {
            let len = read_exact!(stream, [0]).map_err(AddrError::DomainLenUnreadable)?[0];
            let domain = read_exact!(stream, vec![0u8; len as usize])
                .map_err(AddrError::DomainContentUnreadable)?;
            // make sure the bytes are correct utf8 string
            let domain = String::from_utf8(domain).map_err(AddrError::Utf8)?;

            Addr::Domain(domain)
        }
        _ => return Err(AddrError::IncorrectAddressType),
    };

    // Find port number
    let port = read_exact!(stream, [0u8; 2]).map_err(AddrError::PortNumberUnreadable)?;
    // Convert (u8 * 2) into u16
    let port = (port[0] as u16) << 8 | port[1] as u16;

    // Merge ADDRESS + PORT into a TargetAddr
    let addr: TargetAddr = match addr {
        Addr::V4([a, b, c, d]) => (Ipv4Addr::new(a, b, c, d), port)
            .to_target_addr()
            .map_err(AddrError::AddrConversionFailed)?,
        Addr::V6(x) => (Ipv6Addr::from(x), port)
            .to_target_addr()
            .map_err(AddrError::AddrConversionFailed)?,
        Addr::Domain(domain) => TargetAddr::Domain(domain, port),
    };

    Ok(addr)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rfc1928::consts;
    use tokio::io::AsyncWriteExt;

    async fn read_target_addr(bytes: &[u8]) -> Result<TargetAddr, AddrError> {
        let (mut client, mut server) = tokio::io::duplex(64);
        client.write_all(&bytes[1..]).await.unwrap();
        drop(client);
        read_address(&mut server, bytes[0]).await
    }

    #[tokio::test]
    async fn read_address_ipv4_round_trip() {
        let addr = read_target_addr(&[consts::SOCKS5_ADDR_TYPE_IPV4, 192, 168, 0, 1, 0, 80])
            .await
            .unwrap();
        assert_eq!(addr, TargetAddr::Ip("192.168.0.1:80".parse().unwrap()));
        assert!(addr.is_ip());
        let encoded = addr.to_be_bytes().unwrap();
        assert_eq!(
            encoded,
            vec![consts::SOCKS5_ADDR_TYPE_IPV4, 192, 168, 0, 1, 0, 80,]
        );
    }

    #[tokio::test]
    async fn read_address_ipv6_round_trip() {
        let addr = read_target_addr(&[
            consts::SOCKS5_ADDR_TYPE_IPV6,
            0x20,
            0x01,
            0x0d,
            0xb8,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0x01,
            0x01,
            0xbb,
        ])
        .await
        .unwrap();
        assert_eq!(addr, TargetAddr::Ip("[2001:db8::1]:443".parse().unwrap()));
        let encoded = addr.to_be_bytes().unwrap();
        assert_eq!(
            encoded,
            vec![
                consts::SOCKS5_ADDR_TYPE_IPV6,
                0x20,
                0x01,
                0x0d,
                0xb8,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0x01,
                0x01,
                0xbb,
            ]
        );
    }

    #[tokio::test]
    async fn read_address_domain_round_trip() {
        let addr = read_target_addr(&[
            consts::SOCKS5_ADDR_TYPE_DOMAIN_NAME,
            11,
            b'e',
            b'x',
            b'a',
            b'm',
            b'p',
            b'l',
            b'e',
            b'.',
            b'c',
            b'o',
            b'm',
            0,
            80,
        ])
        .await
        .unwrap();
        assert_eq!(addr, TargetAddr::Domain("example.com".to_owned(), 80));
        assert!(addr.is_domain());
        let encoded = addr.to_be_bytes().unwrap();
        assert_eq!(
            encoded,
            vec![
                consts::SOCKS5_ADDR_TYPE_DOMAIN_NAME,
                11,
                b'e',
                b'x',
                b'a',
                b'm',
                b'p',
                b'l',
                b'e',
                b'.',
                b'c',
                b'o',
                b'm',
                0,
                80
            ]
        );
        assert_eq!(addr.into_string_and_port(), ("example.com".to_owned(), 80));
    }

    #[tokio::test]
    async fn read_address_unknown_atyp_is_incorrect() {
        let err = read_target_addr(&[0x02, 0, 0]).await.unwrap_err();
        assert!(matches!(err, AddrError::IncorrectAddressType));
        assert!(matches!(
            err.to_reply_error(),
            ReplyError::AddressTypeNotSupported
        ));
    }

    #[test]
    fn to_be_bytes_domain_too_long() {
        let long_domain = "a".repeat(256);
        let addr = TargetAddr::Domain(long_domain, 80);
        assert!(matches!(
            addr.to_be_bytes(),
            Err(AddrError::DomainLenTooLong(256))
        ));
    }

    #[test]
    fn to_socket_addrs_domain_is_explicit_resolution_only() {
        let addr = TargetAddr::Domain("example.com".to_owned(), 80);
        assert!(std::net::ToSocketAddrs::to_socket_addrs(&addr).is_err());
        let ip: SocketAddr = "10.0.0.1:80".parse().unwrap();
        let addr = TargetAddr::Ip(ip);
        assert_eq!(
            std::net::ToSocketAddrs::to_socket_addrs(&addr)
                .unwrap()
                .next(),
            Some(ip)
        );
    }

    #[test]
    fn to_target_addr_conversions() {
        assert_eq!(
            ("example.com", 80u16).to_target_addr().unwrap(),
            TargetAddr::Domain("example.com".to_owned(), 80)
        );
        assert_eq!(
            ("1.2.3.4", 80u16).to_target_addr().unwrap(),
            TargetAddr::Ip("1.2.3.4:80".parse().unwrap())
        );
        assert_eq!(
            (IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)), 80u16)
                .to_target_addr()
                .unwrap(),
            TargetAddr::Ip("1.2.3.4:80".parse().unwrap())
        );
        assert_eq!(
            (Ipv6Addr::LOCALHOST, 80u16).to_target_addr().unwrap(),
            TargetAddr::Ip("[::1]:80".parse().unwrap())
        );
        let target = TargetAddr::Domain("example.com".to_owned(), 80);
        assert_eq!(target.to_target_addr().unwrap(), target);
    }
}