pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
//! Runtime-neutral SOCKS5 support for SMTP connections.

use std::{fmt, io, net::SocketAddr, time::Instant};

use futures_lite::io::{AsyncReadExt as _, AsyncWriteExt as _};
use secrecy::{ExposeSecret as _, SecretString};

use crate::runtime::{Connect, Connector, Timer, timeout};

/// A SOCKS5 connector that preserves Pata's resolved-destination safety checks.
pub struct Socks5Connector {
    proxy: SocketAddr,
    connector: Box<dyn Connector>,
    timer: Box<dyn Timer>,
    credentials: Option<Credentials>,
}

impl Socks5Connector {
    /// Wraps a TCP connector and timer with a SOCKS5 handshake.
    #[must_use]
    pub fn new(
        proxy: SocketAddr,
        connector: impl Connector + 'static,
        timer: impl Timer + 'static,
    ) -> Self {
        Self {
            proxy,
            connector: Box::new(connector),
            timer: Box::new(timer),
            credentials: None,
        }
    }

    /// Adds RFC 1929 username/password authentication.
    pub fn credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> io::Result<Self> {
        let username = username.into();
        let password = password.into();
        if username.is_empty()
            || password.is_empty()
            || username.len() > 255
            || password.len() > 255
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "SOCKS5 credentials must contain 1 to 255 bytes",
            ));
        }
        self.credentials = Some(Credentials {
            username: SecretString::from(username),
            password: SecretString::from(password),
        });
        Ok(self)
    }
}

impl Connector for Socks5Connector {
    fn connect(&self, target: SocketAddr, deadline: Instant) -> Connect<'_> {
        Box::pin(async move {
            let mut stream = self.connector.connect(self.proxy, deadline).await?;
            let methods: &[u8] = if self.credentials.is_some() {
                &[5, 1, 2]
            } else {
                &[5, 1, 0]
            };
            exchange(stream.as_mut(), self.timer.as_ref(), deadline, methods, 2)
                .await
                .and_then(|response| match response.as_slice() {
                    [5, 0] if self.credentials.is_none() => Ok(()),
                    [5, 2] if self.credentials.is_some() => Ok(()),
                    _ => Err(permission("SOCKS5 proxy rejected authentication methods")),
                })?;

            if let Some(credentials) = &self.credentials {
                authenticate(stream.as_mut(), self.timer.as_ref(), deadline, credentials).await?;
            }
            connect_target(stream.as_mut(), self.timer.as_ref(), deadline, target).await?;
            Ok(stream)
        })
    }
}

impl fmt::Debug for Socks5Connector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Socks5Connector")
            .field("proxy", &self.proxy)
            .field("authenticated", &self.credentials.is_some())
            .finish_non_exhaustive()
    }
}

struct Credentials {
    username: SecretString,
    password: SecretString,
}

async fn authenticate(
    stream: &mut dyn crate::runtime::Io,
    timer: &dyn Timer,
    deadline: Instant,
    credentials: &Credentials,
) -> io::Result<()> {
    let username = credentials.username.expose_secret().as_bytes();
    let password = credentials.password.expose_secret().as_bytes();
    let mut request = Vec::with_capacity(username.len() + password.len() + 3);
    request.extend_from_slice(&[1, username.len() as u8]);
    request.extend_from_slice(username);
    request.push(password.len() as u8);
    request.extend_from_slice(password);
    let response = exchange(stream, timer, deadline, &request, 2).await?;
    if response == [1, 0] {
        Ok(())
    } else {
        Err(permission("SOCKS5 username/password authentication failed"))
    }
}

async fn connect_target(
    stream: &mut dyn crate::runtime::Io,
    timer: &dyn Timer,
    deadline: Instant,
    target: SocketAddr,
) -> io::Result<()> {
    let mut request = Vec::with_capacity(22);
    request.extend_from_slice(&[5, 1, 0]);
    match target.ip() {
        std::net::IpAddr::V4(address) => {
            request.push(1);
            request.extend_from_slice(&address.octets());
        }
        std::net::IpAddr::V6(address) => {
            request.push(4);
            request.extend_from_slice(&address.octets());
        }
    }
    request.extend_from_slice(&target.port().to_be_bytes());
    write(stream, timer, deadline, &request).await?;

    let header = read(stream, timer, deadline, 4).await?;
    if header[0] != 5 || header[2] != 0 {
        return Err(invalid_data("SOCKS5 proxy returned an invalid reply"));
    }
    if header[1] != 0 {
        return Err(refused("SOCKS5 proxy could not connect to the destination"));
    }
    let address_length = match header[3] {
        1 => 4,
        4 => 16,
        3 => {
            let length = usize::from(read(stream, timer, deadline, 1).await?[0]);
            if length == 0 {
                return Err(invalid_data("SOCKS5 proxy returned an empty domain name"));
            }
            length
        }
        _ => {
            return Err(invalid_data(
                "SOCKS5 proxy returned an invalid address type",
            ));
        }
    };
    let _ = read(stream, timer, deadline, address_length + 2).await?;
    Ok(())
}

async fn exchange(
    stream: &mut dyn crate::runtime::Io,
    timer: &dyn Timer,
    deadline: Instant,
    request: &[u8],
    response_length: usize,
) -> io::Result<Vec<u8>> {
    write(stream, timer, deadline, request).await?;
    read(stream, timer, deadline, response_length).await
}

async fn write(
    stream: &mut dyn crate::runtime::Io,
    timer: &dyn Timer,
    deadline: Instant,
    bytes: &[u8],
) -> io::Result<()> {
    let duration = remaining(deadline)?;
    timeout(timer, duration, stream.write_all(bytes)).await??;
    let duration = remaining(deadline)?;
    timeout(timer, duration, stream.flush()).await??;
    Ok(())
}

async fn read(
    stream: &mut dyn crate::runtime::Io,
    timer: &dyn Timer,
    deadline: Instant,
    length: usize,
) -> io::Result<Vec<u8>> {
    let mut response = vec![0; length];
    let duration = remaining(deadline)?;
    timeout(timer, duration, stream.read_exact(&mut response)).await??;
    Ok(response)
}

fn remaining(deadline: Instant) -> io::Result<std::time::Duration> {
    deadline
        .checked_duration_since(Instant::now())
        .filter(|duration| !duration.is_zero())
        .ok_or_else(|| io::Error::new(io::ErrorKind::TimedOut, "SOCKS5 handshake deadline expired"))
}

fn refused(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::ConnectionRefused, message)
}

fn permission(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::PermissionDenied, message)
}

fn invalid_data(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

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

    #[test]
    fn debug_never_contains_proxy_credentials() {
        struct UnusedConnector;
        impl Connector for UnusedConnector {
            fn connect(&self, _address: SocketAddr, _deadline: Instant) -> Connect<'_> {
                Box::pin(async { Err(io::Error::other("unused")) })
            }
        }
        struct UnusedTimer;
        impl Timer for UnusedTimer {
            fn sleep(&self, _duration: std::time::Duration) -> crate::runtime::Sleep {
                Box::pin(std::future::pending())
            }
        }

        let proxy = Socks5Connector::new(
            "127.0.0.1:1080".parse().unwrap(),
            UnusedConnector,
            UnusedTimer,
        )
        .credentials("agent", "secret-value")
        .unwrap();
        let debug = format!("{proxy:?}");

        assert!(!debug.contains("agent"));
        assert!(!debug.contains("secret-value"));
    }

    #[test]
    fn expired_deadline_has_no_remaining_time() {
        let error = remaining(Instant::now()).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::TimedOut);
    }
}