Skip to main content

aria2_protocol/ftp/
tls.rs

1//! FTPS transport primitives and RFC 4217 negotiation.
2//!
3//! This module owns the protocol-level TLS implementation used by FTP
4//! callers.  The download engine is responsible only for choosing when to
5//! use it and mapping application configuration into [`FtpsConfig`].
6
7use std::io;
8use std::path::{Path, PathBuf};
9use std::pin::Pin;
10use std::sync::Arc;
11use std::task::{Context, Poll};
12
13use rustls::DigitallySignedStruct;
14use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
15use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
16use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
17use tokio::net::TcpStream;
18use tokio_rustls::client::TlsStream;
19use tracing::{debug, info, warn};
20
21use crate::crypto::ensure_ring_provider;
22
23/// FTPS (FTP over TLS) configuration per RFC 4217.
24///
25/// The engine maps its user-facing options into this transport configuration.
26/// The protocol module then applies it consistently to control and data
27/// channels.
28#[derive(Debug, Clone)]
29pub struct FtpsConfig {
30    /// Whether the caller requested an FTPS connection.
31    pub enabled: bool,
32    /// Verify the server certificate chain.
33    ///
34    /// Disabling verification is insecure and should only be used when the
35    /// caller explicitly opts into it.
36    pub check_certificate: bool,
37    /// Optional PEM file containing trusted CA certificates.
38    ///
39    /// When omitted, the bundled Mozilla roots are used.
40    pub ca_certificate: Option<PathBuf>,
41    /// Minimum TLS protocol version to negotiate.
42    pub min_tls_version: TlsVersion,
43}
44
45impl Default for FtpsConfig {
46    fn default() -> Self {
47        Self {
48            enabled: false,
49            check_certificate: true,
50            ca_certificate: None,
51            min_tls_version: TlsVersion::Tls12,
52        }
53    }
54}
55
56/// Minimum TLS protocol version for FTPS connections.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
58pub enum TlsVersion {
59    /// TLS 1.2 (RFC 5246).
60    #[default]
61    Tls12,
62    /// TLS 1.3 (RFC 8446).
63    Tls13,
64}
65
66/// Reusable FTPS TLS client for one download attempt.
67///
68/// The connector is built once so control and data-channel handshakes share
69/// the same certificate roots and TLS policy.
70#[derive(Clone)]
71pub struct FtpsClient {
72    connector: tokio_rustls::TlsConnector,
73}
74
75impl FtpsClient {
76    /// Build a client from the caller's FTPS transport configuration.
77    pub fn new(config: &FtpsConfig) -> Result<Self, String> {
78        Ok(Self {
79            connector: build_tls_connector(config)?,
80        })
81    }
82
83    /// Perform a TLS handshake on an FTP control or implicit-FTPS connection.
84    pub async fn perform_tls_handshake(
85        &self,
86        stream: TcpStream,
87        host: &str,
88    ) -> Result<TlsStream<TcpStream>, String> {
89        perform_tls_handshake_with_connector(stream, host, &self.connector).await
90    }
91
92    /// Perform `AUTH TLS`, the TLS handshake, `PBSZ 0`, and `PROT P`.
93    pub async fn upgrade_control_stream(
94        &self,
95        stream: TcpStream,
96        host: &str,
97    ) -> Result<TlsStream<TcpStream>, String> {
98        upgrade_control_stream_with_connector(stream, host, &self.connector).await
99    }
100
101    /// Upgrade a `PROT P` FTP data connection to TLS.
102    pub async fn upgrade_data_stream(
103        &self,
104        stream: TcpStream,
105        host: &str,
106    ) -> Result<TlsStream<TcpStream>, String> {
107        debug!("Upgrading FTP data connection to TLS for {}", host);
108        let tls_stream = self.perform_tls_handshake(stream, host).await?;
109        info!("FTPS data connection TLS handshake completed with {}", host);
110        Ok(tls_stream)
111    }
112}
113
114/// FTP control stream which can be plain TCP or TLS-protected.
115#[derive(Debug)]
116pub enum FtpControlStream {
117    /// Unencrypted FTP control connection.
118    Plain(TcpStream),
119    /// TLS-encrypted FTP control connection.
120    Tls(Box<TlsStream<TcpStream>>),
121}
122
123impl FtpControlStream {
124    /// Returns whether this stream is TLS-protected.
125    pub fn is_tls(&self) -> bool {
126        matches!(self, Self::Tls(_))
127    }
128
129    /// Returns the underlying TCP stream reference.
130    pub fn get_ref(&self) -> Option<&TcpStream> {
131        match self {
132            Self::Plain(stream) => Some(stream),
133            Self::Tls(stream) => Some(stream.get_ref().0),
134        }
135    }
136}
137
138/// FTP data stream which can be plain TCP or protected by `PROT P`.
139#[derive(Debug)]
140pub enum FtpDataStream {
141    /// Unencrypted FTP data connection.
142    Plain(TcpStream),
143    /// TLS-encrypted FTP data connection.
144    Tls(Box<TlsStream<TcpStream>>),
145}
146
147impl FtpDataStream {
148    /// Set TCP_NODELAY on the underlying socket.
149    pub fn set_nodelay(&self, enabled: bool) -> io::Result<()> {
150        match self {
151            Self::Plain(stream) => stream.set_nodelay(enabled),
152            Self::Tls(stream) => stream.get_ref().0.set_nodelay(enabled),
153        }
154    }
155}
156
157fn parse_response_code(response: &str, command: &str) -> Result<u16, String> {
158    let code_bytes = response
159        .as_bytes()
160        .get(..3)
161        .ok_or_else(|| format!("{} response too short: {}", command, response))?;
162    let code_text = std::str::from_utf8(code_bytes)
163        .map_err(|_| format!("Invalid {} response code: {}", command, response))?;
164    code_text
165        .parse()
166        .map_err(|_| format!("Invalid {} response code: {}", command, response))
167}
168
169// =============================================================================
170// TLS connector construction
171// =============================================================================
172
173/// Build a `tokio_rustls::TlsConnector` from an [`FtpsConfig`].
174pub fn build_tls_connector(config: &FtpsConfig) -> Result<tokio_rustls::TlsConnector, String> {
175    use rustls::ClientConfig;
176    use rustls::crypto::ring::default_provider;
177
178    ensure_ring_provider();
179    let mut root_store = rustls::RootCertStore::empty();
180
181    if config.check_certificate {
182        if let Some(ref ca_path) = config.ca_certificate {
183            let certs = load_pem_certs(ca_path)?;
184            let (added, rejected) = root_store.add_parsable_certificates(certs);
185            if added == 0 {
186                return Err(format!(
187                    "No valid CA certificates found in: {} ({} rejected)",
188                    ca_path.display(),
189                    rejected
190                ));
191            }
192            info!(
193                "Loaded {} CA certificate(s) from {} ({} rejected)",
194                added,
195                ca_path.display(),
196                rejected
197            );
198        } else {
199            root_store.roots = webpki_roots::TLS_SERVER_ROOTS.to_vec();
200            if root_store.is_empty() {
201                return Err("No bundled root certificates available".to_string());
202            }
203            debug!(
204                "Using {} bundled Mozilla root certificates",
205                root_store.len()
206            );
207        }
208    } else {
209        warn!("Certificate verification DISABLED — FTPS connection is insecure");
210    }
211
212    let mut client_config = match config.min_tls_version {
213        TlsVersion::Tls12 => ClientConfig::builder()
214            .with_root_certificates(root_store)
215            .with_no_client_auth(),
216        TlsVersion::Tls13 => ClientConfig::builder_with_provider(Arc::new(default_provider()))
217            .with_protocol_versions(&[&rustls::version::TLS13])
218            .map_err(|e| format!("Failed to set TLS 1.3 only: {}", e))?
219            .with_root_certificates(root_store)
220            .with_no_client_auth(),
221    };
222
223    if !config.check_certificate {
224        client_config
225            .dangerous()
226            .set_certificate_verifier(Arc::new(NoCertificateVerification));
227    }
228
229    Ok(tokio_rustls::TlsConnector::from(Arc::new(client_config)))
230}
231
232fn load_pem_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>, String> {
233    use std::io::BufReader as SyncBufReader;
234
235    let file = std::fs::File::open(path).map_err(|e| {
236        format!(
237            "Failed to open CA certificate file {}: {}",
238            path.display(),
239            e
240        )
241    })?;
242
243    let mut reader = SyncBufReader::new(file);
244    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut reader)
245        .collect::<Result<Vec<_>, _>>()
246        .map_err(|e| {
247            format!(
248                "Failed to parse CA certificates from {}: {}",
249                path.display(),
250                e
251            )
252        })?;
253
254    if certs.is_empty() {
255        return Err(format!("No PEM certificates found in {}", path.display()));
256    }
257
258    Ok(certs)
259}
260
261/// Certificate verifier used when certificate checking is explicitly disabled.
262#[derive(Debug)]
263pub(crate) struct NoCertificateVerification;
264
265impl ServerCertVerifier for NoCertificateVerification {
266    fn verify_server_cert(
267        &self,
268        _end_entity: &CertificateDer<'_>,
269        _intermediates: &[CertificateDer<'_>],
270        _server_name: &ServerName<'_>,
271        _ocsp_response: &[u8],
272        _now: UnixTime,
273    ) -> Result<ServerCertVerified, rustls::Error> {
274        Ok(ServerCertVerified::assertion())
275    }
276
277    fn verify_tls12_signature(
278        &self,
279        _message: &[u8],
280        _cert: &CertificateDer<'_>,
281        _dss: &DigitallySignedStruct,
282    ) -> Result<HandshakeSignatureValid, rustls::Error> {
283        Ok(HandshakeSignatureValid::assertion())
284    }
285
286    fn verify_tls13_signature(
287        &self,
288        _message: &[u8],
289        _cert: &CertificateDer<'_>,
290        _dss: &DigitallySignedStruct,
291    ) -> Result<HandshakeSignatureValid, rustls::Error> {
292        Ok(HandshakeSignatureValid::assertion())
293    }
294
295    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
296        rustls::crypto::ring::default_provider()
297            .signature_verification_algorithms
298            .supported_schemes()
299    }
300}
301
302// =============================================================================
303// RFC 4217 control-channel negotiation
304// =============================================================================
305
306/// Negotiate protected FTP data channels on an established control stream.
307///
308/// This sends `PBSZ 0` followed by `PROT P`. It is shared by explicit FTPS
309/// after `AUTH TLS` and implicit FTPS after the initial TLS handshake.
310/// Returning an error for either rejected response keeps callers from
311/// accidentally treating a TLS control channel as a protected FTPS session
312/// when its data channel would still be plaintext.
313pub async fn negotiate_protected_data_channel<R>(reader: &mut R) -> Result<(), String>
314where
315    R: AsyncBufRead + AsyncWrite + Unpin,
316{
317    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
318
319    debug!("Sending PBSZ 0");
320    reader
321        .write_all(b"PBSZ 0\r\n")
322        .await
323        .map_err(|e| format!("Failed to send PBSZ 0: {}", e))?;
324    reader
325        .flush()
326        .await
327        .map_err(|e| format!("Failed to flush PBSZ 0: {}", e))?;
328
329    let mut line_buf = String::new();
330    reader
331        .read_line(&mut line_buf)
332        .await
333        .map_err(|e| format!("Failed to read PBSZ response: {}", e))?;
334    let pbsz_resp = line_buf.trim();
335    debug!("PBSZ response: {}", pbsz_resp);
336    let pbsz_code = parse_response_code(pbsz_resp, "PBSZ")?;
337    if pbsz_code != 200 {
338        return Err(format!(
339            "PBSZ 0 rejected by server: {} (expected 200)",
340            pbsz_resp
341        ));
342    }
343
344    debug!("Sending PROT P");
345    reader
346        .write_all(b"PROT P\r\n")
347        .await
348        .map_err(|e| format!("Failed to send PROT P: {}", e))?;
349    reader
350        .flush()
351        .await
352        .map_err(|e| format!("Failed to flush PROT P: {}", e))?;
353
354    line_buf.clear();
355    reader
356        .read_line(&mut line_buf)
357        .await
358        .map_err(|e| format!("Failed to read PROT response: {}", e))?;
359    let prot_resp = line_buf.trim();
360    debug!("PROT response: {}", prot_resp);
361    let prot_code = parse_response_code(prot_resp, "PROT")?;
362    if prot_code != 200 {
363        return Err(format!(
364            "PROT P rejected by server: {} (data channel would be unencrypted)",
365            prot_resp
366        ));
367    }
368
369    info!("PBSZ 0 and PROT P accepted — data channel will be TLS-protected");
370    Ok(())
371}
372
373/// Perform `AUTH TLS`, the TLS handshake, `PBSZ 0`, and `PROT P`.
374pub async fn upgrade_control_stream(
375    stream: TcpStream,
376    host: &str,
377    config: &FtpsConfig,
378) -> Result<TlsStream<TcpStream>, String> {
379    let connector = build_tls_connector(config)?;
380    upgrade_control_stream_with_connector(stream, host, &connector).await
381}
382
383async fn upgrade_control_stream_with_connector(
384    mut stream: TcpStream,
385    host: &str,
386    connector: &tokio_rustls::TlsConnector,
387) -> Result<TlsStream<TcpStream>, String> {
388    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
389
390    debug!("Sending AUTH TLS to {}", host);
391    stream
392        .write_all(b"AUTH TLS\r\n")
393        .await
394        .map_err(|e| format!("Failed to send AUTH TLS: {}", e))?;
395    stream
396        .flush()
397        .await
398        .map_err(|e| format!("Failed to flush AUTH TLS: {}", e))?;
399
400    let mut reader = tokio::io::BufReader::new(stream);
401    let mut line_buf = String::new();
402    reader
403        .read_line(&mut line_buf)
404        .await
405        .map_err(|e| format!("Failed to read AUTH TLS response: {}", e))?;
406
407    let response = line_buf.trim();
408    debug!("AUTH TLS response: {}", response);
409    let code = parse_response_code(response, "AUTH TLS")?;
410    if code != 234 {
411        return Err(format!(
412            "AUTH TLS rejected by server: {} (expected 234)",
413            response
414        ));
415    }
416    info!("AUTH TLS accepted (234) — proceeding with TLS handshake");
417
418    let stream = reader.into_inner();
419    let mut tls_stream = perform_tls_handshake_with_connector(stream, host, connector).await?;
420    let mut reader = tokio::io::BufReader::new(&mut tls_stream);
421    negotiate_protected_data_channel(&mut reader).await?;
422    Ok(tls_stream)
423}
424
425/// Perform a TLS handshake on an FTP control or implicit-FTPS connection.
426pub async fn perform_tls_handshake(
427    stream: TcpStream,
428    host: &str,
429    config: &FtpsConfig,
430) -> Result<TlsStream<TcpStream>, String> {
431    let connector = build_tls_connector(config)?;
432    perform_tls_handshake_with_connector(stream, host, &connector).await
433}
434
435async fn perform_tls_handshake_with_connector(
436    stream: TcpStream,
437    host: &str,
438    connector: &tokio_rustls::TlsConnector,
439) -> Result<TlsStream<TcpStream>, String> {
440    let server_name: ServerName<'static> = ServerName::try_from(host.to_string())
441        .map_err(|e| format!("Invalid FTPS server name '{}': {:?}", host, e))?;
442
443    debug!("Starting TLS handshake with {}", host);
444    let tls_stream = connector
445        .connect(server_name, stream)
446        .await
447        .map_err(|e| format!("FTPS TLS handshake failed for {}: {}", host, e))?;
448    info!("TLS handshake completed successfully with {}", host);
449    Ok(tls_stream)
450}
451
452/// Upgrade a `PROT P` FTP data connection to TLS.
453pub async fn upgrade_data_stream(
454    stream: TcpStream,
455    host: &str,
456    config: &FtpsConfig,
457) -> Result<TlsStream<TcpStream>, String> {
458    FtpsClient::new(config)?
459        .upgrade_data_stream(stream, host)
460        .await
461}
462
463impl AsyncRead for FtpControlStream {
464    fn poll_read(
465        self: Pin<&mut Self>,
466        cx: &mut Context<'_>,
467        buf: &mut ReadBuf<'_>,
468    ) -> Poll<io::Result<()>> {
469        match self.get_mut() {
470            Self::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
471            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_read(cx, buf),
472        }
473    }
474}
475
476impl AsyncWrite for FtpControlStream {
477    fn poll_write(
478        self: Pin<&mut Self>,
479        cx: &mut Context<'_>,
480        buf: &[u8],
481    ) -> Poll<io::Result<usize>> {
482        match self.get_mut() {
483            Self::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
484            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_write(cx, buf),
485        }
486    }
487
488    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
489        match self.get_mut() {
490            Self::Plain(stream) => Pin::new(stream).poll_flush(cx),
491            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_flush(cx),
492        }
493    }
494
495    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
496        match self.get_mut() {
497            Self::Plain(stream) => Pin::new(stream).poll_shutdown(cx),
498            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_shutdown(cx),
499        }
500    }
501}
502
503impl AsyncRead for FtpDataStream {
504    fn poll_read(
505        self: Pin<&mut Self>,
506        cx: &mut Context<'_>,
507        buf: &mut ReadBuf<'_>,
508    ) -> Poll<io::Result<()>> {
509        match self.get_mut() {
510            Self::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
511            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_read(cx, buf),
512        }
513    }
514}
515
516impl AsyncWrite for FtpDataStream {
517    fn poll_write(
518        self: Pin<&mut Self>,
519        cx: &mut Context<'_>,
520        buf: &[u8],
521    ) -> Poll<io::Result<usize>> {
522        match self.get_mut() {
523            Self::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
524            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_write(cx, buf),
525        }
526    }
527
528    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
529        match self.get_mut() {
530            Self::Plain(stream) => Pin::new(stream).poll_flush(cx),
531            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_flush(cx),
532        }
533    }
534
535    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
536        match self.get_mut() {
537            Self::Plain(stream) => Pin::new(stream).poll_shutdown(cx),
538            Self::Tls(stream) => Pin::new(stream.as_mut()).poll_shutdown(cx),
539        }
540    }
541}
542
543#[cfg(test)]
544mod tests;