alksocks 0.3.0

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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! The RFC 1928 core: a targeted fork of fast-socks5 v1.0.0's
//! `T`-generic subset (MIT, third-party upstream —
//! github.com/dizda/fast-socks5; `/workspace/fast-socks5` is the
//! read-only reference checkout, kept for differential testing of
//! RFC edge cases).
//!
//! Arrived by extraction (ADR-011 §Amendment, docs/architecture/
//! decisions/011-inline-vendor.md): only the code already generic
//! over `T: AsyncRead + AsyncWrite + Unpin` was copied in-tree — the
//! kernel-net handlers, the `socks4` module, and the legacy `Config`/
//! `Authentication` layer were **not** copied. The extraction cut,
//! the fork's two carried changes (BIND support, `new_reply`
//! publication), and the extraction-time adjustments (no `anyhow`,
//! no `log`, no `async-trait`) are recorded in
//! `docs/architecture/rfc1928.md`.
//!
//! Ownership (ADR-013, docs/architecture/decisions/013-targeted-fork.md):
//! this is fully owned code — project conventions apply
//! unconditionally (no vendor carve-outs, no verbatim preservation,
//! no lint-allow posture). Fork point: the tree as of the
//! extraction-review commit (`5b18d4d`); extraction provenance in
//! git history (`57b107b..5b18d4d`). A future upstream fix that
//! matters is hand-ported against the reference checkout and guarded
//! by the differential suite.
//!
//! This file is upstream's `src/lib.rs` vocabulary region (the
//! wire-vocabulary extraction task): the `consts`, the command/auth
//! enums, the reply-code codec, the UDP datagram codec, and the error
//! vocabulary pruned to the region's consumers. The typestate
//! (upstream `server.rs`, minus the cut regions) lives in
//! [`server`]; the client session (upstream `client.rs`, the
//! `use_stream` path + the `AsyncRead`/`AsyncWrite` impls) lives in
//! [`client`].
//!
//! License: upstream is MIT with no per-file headers — the bundled
//! notice (`LICENSE`, this module's directory, v1.0.0 attribution +
//! the fork-point statement) is the license obligation's carrier.
//!
//! Maintenance posture: this code co-evolves with the wrapper and is
//! the crate's only RFC 1928 wire vocabulary ("no second codec,
//! ever" — ADR-011's rationale, carried). Nothing is absorbed
//! silently from upstream; nothing waits on upstream.

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

use std::fmt;
use std::io;
use thiserror::Error;
use util::stream::read_exact;
use util::target_addr::read_address;
use util::target_addr::AddrError;
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,
}

impl Socks5Command {
    #[inline]
    #[rustfmt::skip]
    pub 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]
    pub 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
        }
    }
}

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"),
        }
    }
}

#[derive(Error, Debug)]
pub enum SocksError {
    #[error("i/o error: {0}")]
    Io(#[from] io::Error),
    #[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 rejected `{0}`")]
    AuthenticationRejected(String),
    #[error("Target addr should be present")]
    MissingTargetAddr,

    #[error(transparent)]
    ServerError(#[from] server::SocksServerError),

    #[error(transparent)]
    UdpHeaderError(#[from] UdpHeaderError),

    #[error(transparent)]
    AddrError(#[from] AddrError),

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

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,
}

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,
        }
    }

    /// Map a wire reply code to its variant. Codes outside the RFC
    /// table (`0x09`–`0xFF`, unassigned per RFC 1928 §6) map to
    /// `GeneralFailure` — the RFC's catch-all — instead of panicking:
    /// the value comes off the wire (the client session feeds the raw
    /// reply byte here), so a misbehaving peer must surface as a typed
    /// error, never a panic. Upstream's `unreachable!()` arm was the
    /// review's F-1 correction.
    #[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::GeneralFailure,
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum UdpHeaderError {
    #[error(transparent)]
    AddrError(#[from] AddrError),
    #[error("could not convert target addr: {0}")]
    ToTargetAddr(#[source] io::Error),
    #[error("could not read UDP header: {0}")]
    ReadingError(#[source] io::Error),
    #[error("does not match the expected reserved field")]
    GarbageInReserved,
}

/// 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>, UdpHeaderError> {
    let mut header = vec![
        0, 0, // RSV
        0, // FRAG
    ];
    header.append(
        &mut target_addr
            .to_target_addr()
            .map_err(UdpHeaderError::ToTargetAddr)?
            .to_be_bytes()?,
    );

    Ok(header)
}

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

    if !rsv.eq(&[0u8; 2]) {
        return Err(UdpHeaderError::GarbageInReserved);
    }

    let [frag, atyp] = read_exact!(req, [0u8; 2]).map_err(UdpHeaderError::ReadingError)?;

    let target_addr = read_address(&mut req, atyp).await?;

    Ok((frag, target_addr, req))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn socks5_command_mapping() {
        assert_eq!(
            Socks5Command::TCPConnect.as_u8(),
            consts::SOCKS5_CMD_TCP_CONNECT
        );
        assert_eq!(Socks5Command::TCPBind.as_u8(), consts::SOCKS5_CMD_TCP_BIND);
        assert_eq!(
            Socks5Command::UDPAssociate.as_u8(),
            consts::SOCKS5_CMD_UDP_ASSOCIATE
        );
        assert_eq!(
            Socks5Command::from_u8(consts::SOCKS5_CMD_TCP_CONNECT),
            Some(Socks5Command::TCPConnect)
        );
        assert_eq!(
            Socks5Command::from_u8(consts::SOCKS5_CMD_TCP_BIND),
            Some(Socks5Command::TCPBind)
        );
        assert_eq!(
            Socks5Command::from_u8(consts::SOCKS5_CMD_UDP_ASSOCIATE),
            Some(Socks5Command::UDPAssociate)
        );
        assert_eq!(Socks5Command::from_u8(0x00), None);
        assert_eq!(Socks5Command::from_u8(0x04), None);
    }

    #[test]
    fn reply_error_mapping_table() {
        let table = [
            (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,
            ),
        ];
        for (reply, code) in table {
            assert_eq!(reply.as_u8(), code);
            assert!(matches!(ReplyError::from_u8(code), r if r.as_u8() == code));
        }
    }

    /// F-1 (review): unassigned reply codes (`0x09`–`0xFF`, RFC 1928
    /// §6) surface as `GeneralFailure` — the RFC's catch-all — never
    /// a panic. Upstream's `unreachable!()` arm was removed: the code
    /// comes off the wire (`read_request_reply` → `from_u8`), so a
    /// misbehaving peer must not crash the consumer task.
    #[test]
    fn reply_error_unassigned_codes_map_to_general_failure() {
        for code in [0x09u8, 0x0a, 0x7f, 0xff] {
            assert_eq!(ReplyError::from_u8(code).as_u8(), 0x01);
        }
    }

    #[tokio::test]
    async fn udp_header_round_trip_ip() {
        let target = TargetAddr::Ip("192.168.0.1:80".parse().unwrap());
        let header = new_udp_header(target.clone()).unwrap();
        assert_eq!(header, vec![0, 0, 0, 1, 192, 168, 0, 1, 0, 80]);

        let (frag, parsed_target, payload) = parse_udp_request(&header).await.unwrap();
        assert_eq!(frag, 0);
        assert_eq!(parsed_target, target);
        assert!(payload.is_empty());
    }

    #[tokio::test]
    async fn udp_header_round_trip_domain() {
        let target = TargetAddr::Domain("example.com".to_owned(), 53);
        let header = new_udp_header(target.clone()).unwrap();
        assert_eq!(
            header,
            vec![
                0,
                0,
                0,
                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,
                53,
            ]
        );

        let (frag, parsed_target, payload) = parse_udp_request(&header).await.unwrap();
        assert_eq!(frag, 0);
        assert_eq!(parsed_target, target);
        assert!(payload.is_empty());
    }

    #[tokio::test]
    async fn udp_header_rejects_garbage_reserved() {
        let mut header = new_udp_header(TargetAddr::Domain("example.com".to_owned(), 53)).unwrap();
        header[1] = 0xff;
        let err = parse_udp_request(&header).await.unwrap_err();
        assert!(matches!(err, UdpHeaderError::GarbageInReserved));
    }

    #[tokio::test]
    async fn udp_header_carries_fragment_and_payload() {
        let mut frame = new_udp_header(TargetAddr::Ip("10.0.0.1:53".parse().unwrap())).unwrap();
        frame[2] = 3;
        frame.extend_from_slice(b"hello");
        let (frag, target, payload) = parse_udp_request(&frame).await.unwrap();
        assert_eq!(frag, 3);
        assert_eq!(target, TargetAddr::Ip("10.0.0.1:53".parse().unwrap()));
        assert_eq!(payload, b"hello");
    }

    #[tokio::test]
    async fn udp_header_rejects_unknown_address_type() {
        let frame = vec![0, 0, 0, 0x02, 1, 2, 3, 4, 0, 0];
        let err = parse_udp_request(&frame).await.unwrap_err();
        assert!(matches!(err, UdpHeaderError::AddrError(_)));
    }

    #[test]
    fn socks_error_from_variants() {
        let err: SocksError = UdpHeaderError::GarbageInReserved.into();
        assert!(matches!(err, SocksError::UdpHeaderError(_)));
        let err: SocksError = AddrError::IncorrectAddressType.into();
        assert!(matches!(err, SocksError::AddrError(_)));
        let err: SocksError = ReplyError::CommandNotSupported.into();
        assert!(matches!(err, SocksError::ReplyError(_)));
    }
}