1use 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
21#[derive(Debug, Clone)]
27pub struct FtpsConfig {
28 pub enabled: bool,
30 pub check_certificate: bool,
35 pub ca_certificate: Option<PathBuf>,
39 pub min_tls_version: TlsVersion,
41}
42
43impl Default for FtpsConfig {
44 fn default() -> Self {
45 Self {
46 enabled: false,
47 check_certificate: true,
48 ca_certificate: None,
49 min_tls_version: TlsVersion::Tls12,
50 }
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum TlsVersion {
57 #[default]
59 Tls12,
60 Tls13,
62}
63
64#[derive(Debug)]
66pub enum FtpControlStream {
67 Plain(TcpStream),
69 Tls(Box<TlsStream<TcpStream>>),
71}
72
73impl FtpControlStream {
74 pub fn is_tls(&self) -> bool {
76 matches!(self, Self::Tls(_))
77 }
78
79 pub fn get_ref(&self) -> Option<&TcpStream> {
81 match self {
82 Self::Plain(stream) => Some(stream),
83 Self::Tls(stream) => Some(stream.get_ref().0),
84 }
85 }
86}
87
88#[derive(Debug)]
90pub enum FtpDataStream {
91 Plain(TcpStream),
93 Tls(Box<TlsStream<TcpStream>>),
95}
96
97impl FtpDataStream {
98 pub fn set_nodelay(&self, enabled: bool) -> io::Result<()> {
100 match self {
101 Self::Plain(stream) => stream.set_nodelay(enabled),
102 Self::Tls(stream) => stream.get_ref().0.set_nodelay(enabled),
103 }
104 }
105}
106
107fn parse_response_code(response: &str, command: &str) -> Result<u16, String> {
108 let code_bytes = response
109 .as_bytes()
110 .get(..3)
111 .ok_or_else(|| format!("{} response too short: {}", command, response))?;
112 let code_text = std::str::from_utf8(code_bytes)
113 .map_err(|_| format!("Invalid {} response code: {}", command, response))?;
114 code_text
115 .parse()
116 .map_err(|_| format!("Invalid {} response code: {}", command, response))
117}
118
119pub fn build_tls_connector(config: &FtpsConfig) -> Result<tokio_rustls::TlsConnector, String> {
125 use rustls::ClientConfig;
126 use rustls::crypto::ring::default_provider;
127
128 let _ = default_provider().install_default();
129 let mut root_store = rustls::RootCertStore::empty();
130
131 if config.check_certificate {
132 if let Some(ref ca_path) = config.ca_certificate {
133 let certs = load_pem_certs(ca_path)?;
134 let (added, rejected) = root_store.add_parsable_certificates(certs);
135 if added == 0 {
136 return Err(format!(
137 "No valid CA certificates found in: {} ({} rejected)",
138 ca_path.display(),
139 rejected
140 ));
141 }
142 info!(
143 "Loaded {} CA certificate(s) from {} ({} rejected)",
144 added,
145 ca_path.display(),
146 rejected
147 );
148 } else {
149 root_store.roots = webpki_roots::TLS_SERVER_ROOTS.to_vec();
150 if root_store.is_empty() {
151 return Err("No bundled root certificates available".to_string());
152 }
153 debug!(
154 "Using {} bundled Mozilla root certificates",
155 root_store.len()
156 );
157 }
158 } else {
159 warn!("Certificate verification DISABLED — FTPS connection is insecure");
160 }
161
162 let mut client_config = match config.min_tls_version {
163 TlsVersion::Tls12 => ClientConfig::builder()
164 .with_root_certificates(root_store)
165 .with_no_client_auth(),
166 TlsVersion::Tls13 => ClientConfig::builder_with_provider(Arc::new(default_provider()))
167 .with_protocol_versions(&[&rustls::version::TLS13])
168 .map_err(|e| format!("Failed to set TLS 1.3 only: {}", e))?
169 .with_root_certificates(root_store)
170 .with_no_client_auth(),
171 };
172
173 if !config.check_certificate {
174 client_config
175 .dangerous()
176 .set_certificate_verifier(Arc::new(NoCertificateVerification));
177 }
178
179 Ok(tokio_rustls::TlsConnector::from(Arc::new(client_config)))
180}
181
182fn load_pem_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>, String> {
183 use std::io::BufReader as SyncBufReader;
184
185 let file = std::fs::File::open(path).map_err(|e| {
186 format!(
187 "Failed to open CA certificate file {}: {}",
188 path.display(),
189 e
190 )
191 })?;
192
193 let mut reader = SyncBufReader::new(file);
194 let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut reader)
195 .collect::<Result<Vec<_>, _>>()
196 .map_err(|e| {
197 format!(
198 "Failed to parse CA certificates from {}: {}",
199 path.display(),
200 e
201 )
202 })?;
203
204 if certs.is_empty() {
205 return Err(format!("No PEM certificates found in {}", path.display()));
206 }
207
208 Ok(certs)
209}
210
211#[derive(Debug)]
213pub(crate) struct NoCertificateVerification;
214
215impl ServerCertVerifier for NoCertificateVerification {
216 fn verify_server_cert(
217 &self,
218 _end_entity: &CertificateDer<'_>,
219 _intermediates: &[CertificateDer<'_>],
220 _server_name: &ServerName<'_>,
221 _ocsp_response: &[u8],
222 _now: UnixTime,
223 ) -> Result<ServerCertVerified, rustls::Error> {
224 Ok(ServerCertVerified::assertion())
225 }
226
227 fn verify_tls12_signature(
228 &self,
229 _message: &[u8],
230 _cert: &CertificateDer<'_>,
231 _dss: &DigitallySignedStruct,
232 ) -> Result<HandshakeSignatureValid, rustls::Error> {
233 Ok(HandshakeSignatureValid::assertion())
234 }
235
236 fn verify_tls13_signature(
237 &self,
238 _message: &[u8],
239 _cert: &CertificateDer<'_>,
240 _dss: &DigitallySignedStruct,
241 ) -> Result<HandshakeSignatureValid, rustls::Error> {
242 Ok(HandshakeSignatureValid::assertion())
243 }
244
245 fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
246 rustls::crypto::ring::default_provider()
247 .signature_verification_algorithms
248 .supported_schemes()
249 }
250}
251
252pub async fn negotiate_protected_data_channel<R>(reader: &mut R) -> Result<(), String>
264where
265 R: AsyncBufRead + AsyncWrite + Unpin,
266{
267 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
268
269 debug!("Sending PBSZ 0");
270 reader
271 .write_all(b"PBSZ 0\r\n")
272 .await
273 .map_err(|e| format!("Failed to send PBSZ 0: {}", e))?;
274 reader
275 .flush()
276 .await
277 .map_err(|e| format!("Failed to flush PBSZ 0: {}", e))?;
278
279 let mut line_buf = String::new();
280 reader
281 .read_line(&mut line_buf)
282 .await
283 .map_err(|e| format!("Failed to read PBSZ response: {}", e))?;
284 let pbsz_resp = line_buf.trim();
285 debug!("PBSZ response: {}", pbsz_resp);
286 let pbsz_code = parse_response_code(pbsz_resp, "PBSZ")?;
287 if pbsz_code != 200 {
288 return Err(format!(
289 "PBSZ 0 rejected by server: {} (expected 200)",
290 pbsz_resp
291 ));
292 }
293
294 debug!("Sending PROT P");
295 reader
296 .write_all(b"PROT P\r\n")
297 .await
298 .map_err(|e| format!("Failed to send PROT P: {}", e))?;
299 reader
300 .flush()
301 .await
302 .map_err(|e| format!("Failed to flush PROT P: {}", e))?;
303
304 line_buf.clear();
305 reader
306 .read_line(&mut line_buf)
307 .await
308 .map_err(|e| format!("Failed to read PROT response: {}", e))?;
309 let prot_resp = line_buf.trim();
310 debug!("PROT response: {}", prot_resp);
311 let prot_code = parse_response_code(prot_resp, "PROT")?;
312 if prot_code != 200 {
313 return Err(format!(
314 "PROT P rejected by server: {} (data channel would be unencrypted)",
315 prot_resp
316 ));
317 }
318
319 info!("PBSZ 0 and PROT P accepted — data channel will be TLS-protected");
320 Ok(())
321}
322
323pub async fn upgrade_control_stream(
325 mut stream: TcpStream,
326 host: &str,
327 config: &FtpsConfig,
328) -> Result<TlsStream<TcpStream>, String> {
329 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
330
331 debug!("Sending AUTH TLS to {}", host);
332 stream
333 .write_all(b"AUTH TLS\r\n")
334 .await
335 .map_err(|e| format!("Failed to send AUTH TLS: {}", e))?;
336 stream
337 .flush()
338 .await
339 .map_err(|e| format!("Failed to flush AUTH TLS: {}", e))?;
340
341 let mut reader = tokio::io::BufReader::new(stream);
342 let mut line_buf = String::new();
343 reader
344 .read_line(&mut line_buf)
345 .await
346 .map_err(|e| format!("Failed to read AUTH TLS response: {}", e))?;
347
348 let response = line_buf.trim();
349 debug!("AUTH TLS response: {}", response);
350 let code = parse_response_code(response, "AUTH TLS")?;
351 if code != 234 {
352 return Err(format!(
353 "AUTH TLS rejected by server: {} (expected 234)",
354 response
355 ));
356 }
357 info!("AUTH TLS accepted (234) — proceeding with TLS handshake");
358
359 let stream = reader.into_inner();
360 let mut tls_stream = perform_tls_handshake(stream, host, config).await?;
361 let mut reader = tokio::io::BufReader::new(&mut tls_stream);
362 negotiate_protected_data_channel(&mut reader).await?;
363 Ok(tls_stream)
364}
365
366pub async fn perform_tls_handshake(
368 stream: TcpStream,
369 host: &str,
370 config: &FtpsConfig,
371) -> Result<TlsStream<TcpStream>, String> {
372 let connector = build_tls_connector(config)?;
373 let server_name: ServerName<'static> = ServerName::try_from(host.to_string())
374 .map_err(|e| format!("Invalid FTPS server name '{}': {:?}", host, e))?;
375
376 debug!("Starting TLS handshake with {}", host);
377 let tls_stream = connector
378 .connect(server_name, stream)
379 .await
380 .map_err(|e| format!("FTPS TLS handshake failed for {}: {}", host, e))?;
381 info!("TLS handshake completed successfully with {}", host);
382 Ok(tls_stream)
383}
384
385pub async fn upgrade_data_stream(
387 stream: TcpStream,
388 host: &str,
389 config: &FtpsConfig,
390) -> Result<TlsStream<TcpStream>, String> {
391 debug!("Upgrading FTP data connection to TLS for {}", host);
392 let tls_stream = perform_tls_handshake(stream, host, config).await?;
393 info!("FTPS data connection TLS handshake completed with {}", host);
394 Ok(tls_stream)
395}
396
397impl AsyncRead for FtpControlStream {
398 fn poll_read(
399 self: Pin<&mut Self>,
400 cx: &mut Context<'_>,
401 buf: &mut ReadBuf<'_>,
402 ) -> Poll<io::Result<()>> {
403 match self.get_mut() {
404 Self::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
405 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_read(cx, buf),
406 }
407 }
408}
409
410impl AsyncWrite for FtpControlStream {
411 fn poll_write(
412 self: Pin<&mut Self>,
413 cx: &mut Context<'_>,
414 buf: &[u8],
415 ) -> Poll<io::Result<usize>> {
416 match self.get_mut() {
417 Self::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
418 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_write(cx, buf),
419 }
420 }
421
422 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
423 match self.get_mut() {
424 Self::Plain(stream) => Pin::new(stream).poll_flush(cx),
425 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_flush(cx),
426 }
427 }
428
429 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
430 match self.get_mut() {
431 Self::Plain(stream) => Pin::new(stream).poll_shutdown(cx),
432 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_shutdown(cx),
433 }
434 }
435}
436
437impl AsyncRead for FtpDataStream {
438 fn poll_read(
439 self: Pin<&mut Self>,
440 cx: &mut Context<'_>,
441 buf: &mut ReadBuf<'_>,
442 ) -> Poll<io::Result<()>> {
443 match self.get_mut() {
444 Self::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
445 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_read(cx, buf),
446 }
447 }
448}
449
450impl AsyncWrite for FtpDataStream {
451 fn poll_write(
452 self: Pin<&mut Self>,
453 cx: &mut Context<'_>,
454 buf: &[u8],
455 ) -> Poll<io::Result<usize>> {
456 match self.get_mut() {
457 Self::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
458 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_write(cx, buf),
459 }
460 }
461
462 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
463 match self.get_mut() {
464 Self::Plain(stream) => Pin::new(stream).poll_flush(cx),
465 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_flush(cx),
466 }
467 }
468
469 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
470 match self.get_mut() {
471 Self::Plain(stream) => Pin::new(stream).poll_shutdown(cx),
472 Self::Tls(stream) => Pin::new(stream.as_mut()).poll_shutdown(cx),
473 }
474 }
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 #[test]
482 fn ftps_config_default() {
483 let config = FtpsConfig::default();
484 assert!(!config.enabled);
485 assert!(config.check_certificate);
486 assert!(config.ca_certificate.is_none());
487 assert_eq!(config.min_tls_version, TlsVersion::Tls12);
488 }
489
490 #[test]
491 fn tls_version_default() {
492 assert_eq!(TlsVersion::default(), TlsVersion::Tls12);
493 }
494
495 #[test]
496 fn response_code_requires_ascii_three_digit_prefix() {
497 assert_eq!(parse_response_code("200 OK", "TEST").unwrap(), 200);
498 assert!(parse_response_code("20", "TEST").is_err());
499 assert!(parse_response_code("é00 OK", "TEST").is_err());
500 assert!(parse_response_code("ABC OK", "TEST").is_err());
501 }
502
503 #[test]
504 fn connector_builds_with_check_enabled() {
505 let config = FtpsConfig {
506 enabled: true,
507 check_certificate: true,
508 ca_certificate: None,
509 min_tls_version: TlsVersion::Tls12,
510 };
511 assert!(build_tls_connector(&config).is_ok());
512 }
513
514 #[test]
515 fn connector_builds_with_check_disabled() {
516 let config = FtpsConfig {
517 enabled: true,
518 check_certificate: false,
519 ca_certificate: None,
520 min_tls_version: TlsVersion::Tls12,
521 };
522 assert!(build_tls_connector(&config).is_ok());
523 }
524
525 #[test]
526 fn connector_rejects_missing_ca_file() {
527 let config = FtpsConfig {
528 enabled: true,
529 check_certificate: true,
530 ca_certificate: Some(PathBuf::from("/nonexistent/ca.pem")),
531 min_tls_version: TlsVersion::Tls12,
532 };
533 assert!(build_tls_connector(&config).is_err());
534 }
535
536 #[test]
537 fn connector_builds_with_tls13() {
538 let config = FtpsConfig {
539 enabled: true,
540 check_certificate: true,
541 ca_certificate: None,
542 min_tls_version: TlsVersion::Tls13,
543 };
544 assert!(build_tls_connector(&config).is_ok());
545 }
546
547 #[tokio::test]
548 async fn protected_data_channel_negotiation_requires_both_responses() {
549 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
550
551 let (client, server) = tokio::io::duplex(256);
552 let server = tokio::spawn(async move {
553 let mut reader = tokio::io::BufReader::new(server);
554 let mut line = String::new();
555 reader.read_line(&mut line).await.unwrap();
556 assert_eq!(line, "PBSZ 0\r\n");
557 reader
558 .get_mut()
559 .write_all(b"200 PBSZ ok\r\n")
560 .await
561 .unwrap();
562 line.clear();
563 reader.read_line(&mut line).await.unwrap();
564 assert_eq!(line, "PROT P\r\n");
565 reader
566 .get_mut()
567 .write_all(b"200 PROT ok\r\n")
568 .await
569 .unwrap();
570 });
571
572 let mut client = tokio::io::BufReader::new(client);
573 negotiate_protected_data_channel(&mut client).await.unwrap();
574 server.await.unwrap();
575 }
576
577 #[tokio::test]
578 async fn protected_data_channel_negotiation_fails_closed_on_prot_rejection() {
579 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
580
581 let (client, server) = tokio::io::duplex(256);
582 let server = tokio::spawn(async move {
583 let mut reader = tokio::io::BufReader::new(server);
584 let mut line = String::new();
585 reader.read_line(&mut line).await.unwrap();
586 reader
587 .get_mut()
588 .write_all(b"200 PBSZ ok\r\n")
589 .await
590 .unwrap();
591 line.clear();
592 reader.read_line(&mut line).await.unwrap();
593 reader
594 .get_mut()
595 .write_all(b"534 PROT rejected\r\n")
596 .await
597 .unwrap();
598 });
599
600 let mut client = tokio::io::BufReader::new(client);
601 let result = negotiate_protected_data_channel(&mut client).await;
602 assert!(result.is_err());
603 server.await.unwrap();
604 }
605}