Skip to main content

karyon_net/layers/proxy/
socks5.rs

1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use karyon_core::async_runtime::io::{AsyncReadExt, AsyncWriteExt};
4
5use crate::{ByteStream, Error, Result, layer::ClientLayer};
6
7const SOCKS5_VERSION: u8 = 0x05;
8const NO_AUTH: u8 = 0x00;
9const CMD_CONNECT: u8 = 0x01;
10const ATYPE_IPV4: u8 = 0x01;
11const ATYPE_DOMAIN: u8 = 0x03;
12const ATYPE_IPV6: u8 = 0x04;
13const REPLY_SUCCESS: u8 = 0x00;
14
15/// SOCKS5 proxy layer (RFC 1928). Client-only.
16///
17/// Performs the SOCKS5 handshake on the stream (which is already
18/// connected to the proxy) to tunnel through to the target.
19///
20/// # Example
21///
22/// ```no_run
23/// use karyon_net::{tcp, ClientLayer, Endpoint};
24/// use karyon_net::layers::proxy::Socks5Layer;
25///
26/// async {
27///     // Connect to the proxy
28///     let proxy_ep: Endpoint = "tcp://127.0.0.1:1080".parse().unwrap();
29///     let stream = tcp::connect(&proxy_ep, Default::default()).await.unwrap();
30///
31///     // Tunnel to target via SOCKS5
32///     let layer = Socks5Layer::new("example.com", 443);
33///     let tunneled = ClientLayer::handshake(&layer, stream).await.unwrap();
34/// };
35/// ```
36#[derive(Clone)]
37pub struct Socks5Layer {
38    target_host: String,
39    target_port: u16,
40}
41
42impl Socks5Layer {
43    /// Create a new SOCKS5 layer targeting the given host and port.
44    pub fn new(host: &str, port: u16) -> Self {
45        Self {
46            target_host: host.to_string(),
47            target_port: port,
48        }
49    }
50}
51
52impl ClientLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for Socks5Layer {
53    async fn handshake(&self, mut stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
54        // A domain is sent with a one byte length, so it must be 1..=255
55        // bytes. Check before writing anything to the proxy.
56        let host = self.target_host.as_bytes();
57        let host_len = u8::try_from(host.len())
58            .ok()
59            .filter(|len| *len > 0)
60            .ok_or_else(|| Error::Socks5(format!("invalid host length: {}", host.len())))?;
61
62        // Greeting: version + 1 method (no auth).
63        stream.write_all(&[SOCKS5_VERSION, 1, NO_AUTH]).await?;
64        stream.flush().await?;
65
66        // Server picks a method.
67        let mut resp = [0u8; 2];
68        stream.read_exact(&mut resp).await?;
69        if resp[0] != SOCKS5_VERSION || resp[1] != NO_AUTH {
70            return Err(Error::Socks5("server rejected auth method".into()));
71        }
72
73        // Build connect request.
74        let port = self.target_port.to_be_bytes();
75
76        let mut req = vec![SOCKS5_VERSION, CMD_CONNECT, 0x00];
77        if let Ok(ip) = self.target_host.parse::<Ipv4Addr>() {
78            req.push(ATYPE_IPV4);
79            req.extend_from_slice(&ip.octets());
80        } else if let Ok(ip) = self.target_host.parse::<Ipv6Addr>() {
81            req.push(ATYPE_IPV6);
82            req.extend_from_slice(&ip.octets());
83        } else {
84            req.push(ATYPE_DOMAIN);
85            req.push(host_len);
86            req.extend_from_slice(host);
87        }
88        req.extend_from_slice(&port);
89
90        stream.write_all(&req).await?;
91        stream.flush().await?;
92
93        // Read reply header (4 bytes minimum).
94        let mut reply = [0u8; 4];
95        stream.read_exact(&mut reply).await?;
96        if reply[0] != SOCKS5_VERSION {
97            return Err(Error::Socks5("invalid reply version".into()));
98        }
99        if reply[1] != REPLY_SUCCESS {
100            return Err(Error::Socks5(format!("connect failed (code {})", reply[1])));
101        }
102
103        // Skip the bound address in the reply.
104        match reply[3] {
105            ATYPE_IPV4 => {
106                let mut skip = [0u8; 4 + 2]; // 4 ip + 2 port
107                stream.read_exact(&mut skip).await?;
108            }
109            ATYPE_DOMAIN => {
110                let mut len = [0u8; 1];
111                stream.read_exact(&mut len).await?;
112                let mut skip = vec![0u8; len[0] as usize + 2];
113                stream.read_exact(&mut skip).await?;
114            }
115            ATYPE_IPV6 => {
116                let mut skip = [0u8; 16 + 2];
117                stream.read_exact(&mut skip).await?;
118            }
119            atype => {
120                return Err(Error::Socks5(format!(
121                    "unknown address type in reply: {atype:#x}"
122                )));
123            }
124        }
125
126        Ok(stream)
127    }
128}