diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index da57a0e6aa..063dc18fc9 100644 --- a/core/ARCHITECTURE.md +++ b/core/ARCHITECTURE.md @@ -188,10 +188,13 @@ The Windows app runs SSH in process on russh ([ADR 0009](docs/decisions/0009-in- A connection's `TlsConfig` holds the `TlsMode`, an optional CA file, an optional client certificate and key, and an optional server name: - `Disable`: no TLS. +- `Prefer`: TLS when the server offers it, otherwise plain, and the certificate is not checked, as libpq's `prefer` and the mysql client's `PREFERRED` do. Only PostgreSQL and MySQL offer it, since only their protocols ask for TLS before going on without it. - `Require`: encrypted, and the certificate is not checked. - `VerifyFull`: the certificate must chain to a trusted root and carry the server name. - `Strict`: TLS before the first protocol byte, checked as `VerifyFull`. Only SQL Server offers it (TDS 8.0); Microsoft's drivers refuse to combine strict encryption with an unchecked certificate, so there is no unchecked variant. +A new connection starts on the mode the engine's own client starts on, which `DriverCapabilities::new_connection_tls` gives from the driver's `TlsCapabilities::default_mode` and `tls_ports`, the port and the network options ([ADR 0014](docs/decisions/0014-tls-mode-of-a-new-connection.md) has the table). An app keeps a new connection's mode on that default until the user picks one; a saved connection keeps its own. + A CA file goes only with the modes that check the certificate, `VerifyFull` and `Strict`. libpq and the mysql client verify against a CA file given with their require mode, so taking one with `Require` and ignoring it would leave a user who expects a check with none. `validate` refuses the pair, so a saved or imported connection that holds it fails to connect instead of connecting unchecked, and the connect dialog shows the CA row only for the modes that check. The name checked is `NetworkTarget::tls_server_name()`: the override when one is set, otherwise the host the user typed, never the address of a local SSH forward. `TlsConfig::validate` refuses a mode, file or override the driver cannot use on that route, and the connect dialog reads the chosen files up front, so a file with no certificate is named before anything connects. A CA, certificate or key file is read only when it is a regular file of at most 1 MiB, and drivers read it on the blocking pool, so a device or a pipe named in an imported connection can neither fill memory nor hold a connect. diff --git a/core/crates/core/src/capabilities.rs b/core/crates/core/src/capabilities.rs index 36edb7d2e9..a2a1b1e7ae 100644 --- a/core/crates/core/src/capabilities.rs +++ b/core/crates/core/src/capabilities.rs @@ -3,7 +3,7 @@ use crate::config_error::ConfigError; use crate::file_format::FileFormat; use crate::local_socket::{LocalSocket, is_local_socket_host}; use crate::meta::ObjectKind; -use crate::network_options::NetworkOption; +use crate::network_options::{NetworkOption, NetworkOptions}; use crate::tls_capabilities::TlsCapabilities; use crate::tls_mode::TlsMode; use crate::write_ledger::WriteAtomicity; @@ -150,6 +150,22 @@ impl DriverCapabilities { self.network_options.contains(&option) } + /// The TLS mode a new connection to `port` with these options starts + /// on, as the engine's own client starts on it (core ADR 0014). + pub fn new_connection_tls(&self, port: u16, options: &NetworkOptions) -> TlsMode { + let Some(tls) = &self.tls else { + return TlsMode::Disable; + }; + // A DNS seed list is MongoDB's mongodb+srv://, which turns TLS on + // unless told otherwise. + let seed_list = options.dns_seed_list && self.offers(NetworkOption::DnsSeedList); + let tls_only = seed_list || tls.tls_ports.contains(&port); + match tls_only && tls.modes.contains(&TlsMode::VerifyFull) { + true => TlsMode::VerifyFull, + false => tls.default_mode, + } + } + pub fn local_socket(&self) -> Option { self.network_options.iter().find_map(|option| match option { NetworkOption::LocalSocket(socket) => Some(*socket), @@ -168,7 +184,8 @@ impl DriverCapabilities { if tunnelled { return Err(ConfigError::LocalSocketOverSsh); } - if tls.encrypts() && !socket.takes_tls() { + // Prefer goes on in the clear where TLS cannot be had, as libpq does on a socket. + if tls.requires_tls() && !socket.takes_tls() { return Err(ConfigError::TlsOverLocalSocket); } Ok(()) @@ -221,6 +238,51 @@ mod tests { assert!(!file.supports(AuthMode::Password), "a file has no login"); } + #[test] + fn a_new_connection_starts_on_the_engines_default_and_a_seed_list_or_tls_port_on_verify_full() { + let tls = TlsCapabilities { + modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + tls_ports: &[8443], + ca_file: true, + client_identity: true, + server_name_override: crate::ServerNameOverride::AnyRoute, + }; + let document = DriverCapabilities { + tls: Some(tls), + network_options: &[NetworkOption::DnsSeedList], + ..NETWORK + }; + let seed_list = NetworkOptions { + dns_seed_list: true, + ..NetworkOptions::default() + }; + + let plain = NetworkOptions::default(); + + assert_eq!( + NETWORK.new_connection_tls(8443, &seed_list), + TlsMode::Disable, + "no TLS at all" + ); + assert_eq!(document.new_connection_tls(27017, &plain), TlsMode::Disable); + assert_eq!(document.new_connection_tls(27017, &seed_list), TlsMode::VerifyFull); + assert_eq!( + document.new_connection_tls(8443, &plain), + TlsMode::VerifyFull, + "a TLS port" + ); + let no_seed_list = DriverCapabilities { + network_options: &[], + ..document + }; + assert_eq!( + no_seed_list.new_connection_tls(27017, &seed_list), + TlsMode::Disable, + "an option the engine does not read changes nothing" + ); + } + #[test] fn a_network_engine_offers_its_port_and_its_logins() { assert_eq!(NETWORK.default_port(), Some(5432)); @@ -269,6 +331,11 @@ mod tests { with_socket.check_socket_host("/run/postgresql", false, TlsMode::Require), Err(ConfigError::TlsOverLocalSocket) ); + assert_eq!( + with_socket.check_socket_host("/run/postgresql", false, TlsMode::Prefer), + Ok(()), + "a new PostgreSQL connection's default refused its own socket" + ); assert_eq!( with_file.check_socket_host("/run/mysqld/mysqld.sock", false, TlsMode::VerifyFull), Ok(()) diff --git a/core/crates/core/src/connection_url/tests.rs b/core/crates/core/src/connection_url/tests.rs index c0fed3e05e..dbf7218221 100644 --- a/core/crates/core/src/connection_url/tests.rs +++ b/core/crates/core/src/connection_url/tests.rs @@ -121,10 +121,11 @@ fn plus_is_a_plus_and_bad_utf8_is_refused() { } #[test] -fn libpq_modes_map_and_prefer_leaves_the_default() { +fn libpq_modes_map_to_the_core_modes() { assert_eq!(mode("postgresql://db/x?sslmode=disable"), Some(TlsMode::Disable)); - assert_eq!(mode("postgresql://db/x?sslmode=prefer"), None); - assert_eq!(mode("postgresql://db/x?sslmode=allow"), None); + assert_eq!(mode("postgresql://db/x?sslmode=prefer"), Some(TlsMode::Prefer)); + assert_eq!(mode("postgresql://db/x?sslmode=allow"), Some(TlsMode::Prefer)); + assert_eq!(mode("postgresql://db/x?tlsmode=1"), Some(TlsMode::Prefer)); assert_eq!(mode("postgresql://db/x?sslmode=require"), Some(TlsMode::Require)); assert_eq!(mode("postgresql://db/x?SSLMODE=VERIFY_CA"), Some(TlsMode::VerifyFull)); assert_eq!(mode("postgresql://db/x?tlsmode=2"), Some(TlsMode::Require)); @@ -250,7 +251,7 @@ fn a_mysql_socket_is_read_only_for_this_machine() { #[test] fn mysql_tls_spellings_and_the_x_protocol_port() { assert_eq!(mode("mysql://h/db?ssl-mode=DISABLED"), Some(TlsMode::Disable)); - assert_eq!(mode("mysql://h/db?ssl-mode=PREFERRED"), None); + assert_eq!(mode("mysql://h/db?ssl-mode=PREFERRED"), Some(TlsMode::Prefer)); assert_eq!(mode("mysql://h/db?ssl-mode=VERIFY_IDENTITY"), Some(TlsMode::VerifyFull)); assert_eq!( mode("mysql://h/db?ssl=%7B%22rejectUnauthorized%22%3Atrue%7D"), diff --git a/core/crates/core/src/connection_url/tls_hints.rs b/core/crates/core/src/connection_url/tls_hints.rs index 05166ae448..dd2a7d67f2 100644 --- a/core/crates/core/src/connection_url/tls_hints.rs +++ b/core/crates/core/src/connection_url/tls_hints.rs @@ -134,7 +134,7 @@ impl TlsHints { self.weakened = Some(true); } - // No mode leaves it to the form: the URL said nothing, or asked for prefer, which the core does not have. + // No mode leaves it to the form, whose default for the engine stands. pub(super) fn resolve(self) -> UrlTls { let mut wanted = self.mode.or(self.switch).or(self.by_scheme); if self.verify_server && matches!(wanted, None | Some(Wanted::Prefer | Wanted::Require)) { @@ -147,12 +147,12 @@ impl TlsHints { if self.weakened == Some(true) && wanted == Some(Wanted::VerifyFull) { wanted = Some(Wanted::Require); } - let mode = wanted.and_then(|wanted| match wanted { - Wanted::Disable => Some(TlsMode::Disable), - Wanted::Prefer => None, - Wanted::Require => Some(TlsMode::Require), - Wanted::VerifyFull => Some(TlsMode::VerifyFull), - Wanted::Strict => Some(TlsMode::Strict), + let mode = wanted.map(|wanted| match wanted { + Wanted::Disable => TlsMode::Disable, + Wanted::Prefer => TlsMode::Prefer, + Wanted::Require => TlsMode::Require, + Wanted::VerifyFull => TlsMode::VerifyFull, + Wanted::Strict => TlsMode::Strict, }); if mode == Some(TlsMode::Disable) { return UrlTls { diff --git a/core/crates/core/src/tls_capabilities.rs b/core/crates/core/src/tls_capabilities.rs index 022c20e6af..5c1fdadd09 100644 --- a/core/crates/core/src/tls_capabilities.rs +++ b/core/crates/core/src/tls_capabilities.rs @@ -3,6 +3,12 @@ use crate::{ServerNameOverride, TlsMode}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TlsCapabilities { pub modes: &'static [TlsMode], + /// The mode a new connection starts on: the one the engine's own + /// client starts on (core ADR 0014). + pub default_mode: TlsMode, + /// Ports that serve only TLS, where a new connection starts on + /// `VerifyFull` instead. + pub tls_ports: &'static [u16], pub ca_file: bool, pub client_identity: bool, pub server_name_override: ServerNameOverride, diff --git a/core/crates/core/src/tls_config.rs b/core/crates/core/src/tls_config.rs index b06fdd5a02..601daf2fe7 100644 --- a/core/crates/core/src/tls_config.rs +++ b/core/crates/core/src/tls_config.rs @@ -99,12 +99,14 @@ fn validate_server_name( mod tests { use super::*; - const ALL_MODES: &[TlsMode] = &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull]; + const ALL_MODES: &[TlsMode] = &[TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull]; const MSSQL_MODES: &[TlsMode] = &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull, TlsMode::Strict]; const ROUTES: [TransportClass; 2] = [TransportClass::DirectTcp, TransportClass::SshForward]; const POSTGRES: TlsCapabilities = TlsCapabilities { modes: ALL_MODES, + default_mode: TlsMode::Prefer, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, @@ -115,11 +117,14 @@ mod tests { }; const MSSQL: TlsCapabilities = TlsCapabilities { modes: MSSQL_MODES, + default_mode: TlsMode::VerifyFull, client_identity: false, ..POSTGRES }; const VERIFY_ONLY: TlsCapabilities = TlsCapabilities { modes: &[TlsMode::VerifyFull], + default_mode: TlsMode::VerifyFull, + tls_ports: &[], ca_file: false, client_identity: false, server_name_override: ServerNameOverride::Unsupported, @@ -312,6 +317,13 @@ mod tests { TransportClass::DirectTcp, Err(ConfigError::RelativePath), ), + ( + "ca file with prefer, which checks no certificate", + with_ca_file(TlsMode::Prefer, "/etc/tls/ca.pem"), + POSTGRES, + TransportClass::DirectTcp, + Err(ConfigError::CaFileUnsupported), + ), ( "ca file with require, which checks no certificate", with_ca_file(TlsMode::Require, "/etc/tls/ca.pem"), diff --git a/core/crates/core/src/tls_mode.rs b/core/crates/core/src/tls_mode.rs index 9ea0d7271b..e219d4d5ef 100644 --- a/core/crates/core/src/tls_mode.rs +++ b/core/crates/core/src/tls_mode.rs @@ -4,6 +4,10 @@ use serde::{Deserialize, Serialize}; #[serde(rename_all = "snake_case")] pub enum TlsMode { Disable, + /// TLS when the server offers it, otherwise the clear, with the + /// certificate not checked: libpq's `prefer` and the mysql client's + /// `PREFERRED`. + Prefer, Require, VerifyFull, /// TLS before the first protocol byte, as SQL Server's TDS 8.0 strict @@ -19,9 +23,16 @@ impl TlsMode { matches!(self, Self::VerifyFull | Self::Strict) } + /// Whether the client asks the server for TLS. pub fn encrypts(self) -> bool { self != Self::Disable } + + /// Whether a server that does not take TLS is refused rather than + /// reached in the clear. + pub fn requires_tls(self) -> bool { + !matches!(self, Self::Disable | Self::Prefer) + } } #[cfg(test)] @@ -40,4 +51,17 @@ mod tests { Some("\"strict\"") ); } + + #[test] + fn prefer_asks_for_tls_without_requiring_or_checking_it() { + assert!(TlsMode::Prefer.encrypts()); + assert!(!TlsMode::Prefer.requires_tls()); + assert!(!TlsMode::Prefer.verifies_certificate()); + assert!(TlsMode::Require.requires_tls()); + assert!(!TlsMode::Disable.requires_tls()); + assert_eq!( + serde_json::to_string(&TlsMode::Prefer).ok().as_deref(), + Some("\"prefer\"") + ); + } } diff --git a/core/crates/drivers/cassandra/src/capabilities.rs b/core/crates/drivers/cassandra/src/capabilities.rs index b22dfd8599..435670c700 100644 --- a/core/crates/drivers/cassandra/src/capabilities.rs +++ b/core/crates/drivers/cassandra/src/capabilities.rs @@ -19,6 +19,8 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { // checked against the name the driver supplies on every route. tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, diff --git a/core/crates/drivers/cassandra/src/session.rs b/core/crates/drivers/cassandra/src/session.rs index 46bb6c9f47..acfc007f03 100644 --- a/core/crates/drivers/cassandra/src/session.rs +++ b/core/crates/drivers/cassandra/src/session.rs @@ -24,7 +24,7 @@ use tablepro_core::{ APPLICATION_NAME, ConfigError, ConnectEnvironment, Credentials, DriverError, LivenessPolicy, LossPhase, NetworkTarget, ServerCode, ServerInfo, TimeoutPhase, TlsFailure, Transport, }; -use tablepro_net::tls::{TlsSetupError, build_client_config_checking, set_up_off_runtime}; +use tablepro_net::tls::{TlsSetupError, build_client_config_checking, serves_tls, set_up_off_runtime}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; use uuid::Uuid; @@ -53,6 +53,7 @@ pub(crate) struct CqlEndpoint { transport: Arc, login: Option<(String, SecretString)>, tls: Option>, + tls_server_name: String, keyspace: Option, liveness: LivenessPolicy, client_version: String, @@ -69,7 +70,8 @@ impl CqlEndpoint { }; let login = (!username.is_empty()).then(|| (username.clone(), password.clone())); let tls_config = target.tls.clone(); - let name = rustls_pki_types::ServerName::try_from(target.tls_server_name().to_owned()) + let tls_server_name = target.tls_server_name().to_owned(); + let name = rustls_pki_types::ServerName::try_from(tls_server_name.clone()) .map_err(|_| DriverError::Config(ConfigError::InvalidServerName))?; let tls = set_up_off_runtime(move || build_client_config_checking(&tls_config, name).map_err(setup_error)).await?; @@ -77,6 +79,7 @@ impl CqlEndpoint { transport: target.transport.clone(), login, tls, + tls_server_name, keyspace: target.database.clone().filter(|keyspace| !keyspace.is_empty()), liveness, client_version: environment.client_version.clone(), @@ -151,7 +154,11 @@ impl CqlEndpoint { database: keyspace.to_owned(), }); } - return Err(self.explain(&relay, new_session_error(error)).await); + let failed = self.explain(&relay, new_session_error(error)).await; + return Err(tokio::select! { + () = cancel.cancelled() => DriverError::Cancelled, + refused = self.refused_in_the_clear(failed, until) => refused, + }); } Ok(Ok(session)) => session, }; @@ -178,6 +185,21 @@ impl CqlEndpoint { } } + // A node that takes only TLS drops a connect in the clear unanswered, which a handshake of its own tells apart. + async fn refused_in_the_clear(&self, failed: DriverError, until: Instant) -> DriverError { + if self.tls.is_some() || !matches!(failed, DriverError::ConnectionLost { .. }) { + return failed; + } + let within = until.saturating_duration_since(Instant::now()); + if !serves_tls(self.transport.as_ref(), &self.tls_server_name, within).await { + return failed; + } + DriverError::Tls { + failure: TlsFailure::ServerRequiresTls, + detail: failed.to_string(), + } + } + /// A failure the transport knows more about than the closed stream /// the client library saw. A save keeps the outcome it reports, and /// only what stopped it is explained. diff --git a/core/crates/drivers/cassandra/tests/integration/tls.rs b/core/crates/drivers/cassandra/tests/integration/tls.rs index ecadb11250..210c3f1de6 100644 --- a/core/crates/drivers/cassandra/tests/integration/tls.rs +++ b/core/crates/drivers/cassandra/tests/integration/tls.rs @@ -100,9 +100,10 @@ impl TlsConformanceEngine for CqlTlsEngine ErrorCategory { - ErrorCategory::ConnectionLost + ErrorCategory::Tls } } diff --git a/core/crates/drivers/clickhouse/src/capabilities.rs b/core/crates/drivers/clickhouse/src/capabilities.rs index cc1bece9d6..2f7ef077fc 100644 --- a/core/crates/drivers/clickhouse/src/capabilities.rs +++ b/core/crates/drivers/clickhouse/src/capabilities.rs @@ -15,6 +15,10 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { username_required: true, tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + // The HTTPS ports, as clickhouse-client turns TLS on for its secure + // native port. + tls_ports: &[443, 8443], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, diff --git a/core/crates/drivers/clickhouse/src/endpoint.rs b/core/crates/drivers/clickhouse/src/endpoint.rs index 5f43763268..8691fc5796 100644 --- a/core/crates/drivers/clickhouse/src/endpoint.rs +++ b/core/crates/drivers/clickhouse/src/endpoint.rs @@ -2,7 +2,8 @@ use std::sync::Arc; use std::time::Duration; use tablepro_core::{ - ConnectEnvironment, DriverError, LivenessPolicy, NetworkTarget, ServerInfo, TimeoutPhase, TlsMode, Transport, + ConnectEnvironment, DriverError, LivenessPolicy, NetworkTarget, ServerInfo, TimeoutPhase, TlsFailure, TlsMode, + Transport, }; use uuid::Uuid; @@ -30,6 +31,7 @@ pub(crate) struct ClickHouseEndpoint { transport: Arc, liveness: LivenessPolicy, tls_requested: bool, + tls_server_name: String, session_timeout: Duration, read_only: bool, // The login's own `readonly` level, learned on connect. @@ -52,6 +54,7 @@ impl ClickHouseEndpoint { transport: target.transport.clone(), liveness, tls_requested: target.tls.mode != TlsMode::Disable, + tls_server_name: target.tls_server_name().to_owned(), session_timeout: SESSION_TIMEOUT, read_only, login_readonly: 0, @@ -149,7 +152,8 @@ impl ClickHouseEndpoint { tls_requested: self.tls_requested, }; let mapped = missing_at_login(map_error_in(&error, context), self.database.as_deref()); - return Err(self.explain(mapped).await); + let failed = self.explain(mapped).await; + return Err(self.refused_in_the_clear(failed).await); } Ok(Ok(body)) => body, }; @@ -159,6 +163,21 @@ impl ClickHouseEndpoint { Ok((ServerInfo::new("ClickHouse", version, major, minor, patch), database)) } + // A server that takes only TLS drops a login in the clear unanswered, which a handshake of its own tells apart. + async fn refused_in_the_clear(&self, failed: DriverError) -> DriverError { + if self.tls_requested || !matches!(failed, DriverError::ConnectionLost { .. }) { + return failed; + } + let within = self.liveness.login_timeout; + if !tablepro_net::tls::serves_tls(self.transport.as_ref(), &self.tls_server_name, within).await { + return failed; + } + DriverError::Tls { + failure: TlsFailure::ServerRequiresTls, + detail: failed.to_string(), + } + } + /// A stream that closed may be the transport's doing, such as an SSH /// master that exited, which says more than "connection lost". pub(crate) async fn explain(&self, error: DriverError) -> DriverError { diff --git a/core/crates/drivers/clickhouse/tests/integration/tls.rs b/core/crates/drivers/clickhouse/tests/integration/tls.rs index c1fc44ffb6..563dd64269 100644 --- a/core/crates/drivers/clickhouse/tests/integration/tls.rs +++ b/core/crates/drivers/clickhouse/tests/integration/tls.rs @@ -96,9 +96,10 @@ impl TlsConformanceEngine for ClickHouseTlsEngine { } /// Plain HTTP to the HTTPS port fails the server's handshake, and it - /// closes the connection without an HTTP answer. + /// closes the connection without an HTTP answer, then completes the + /// driver's own TLS handshake. fn plaintext_rejection_category(&self) -> ErrorCategory { - ErrorCategory::ConnectionLost + ErrorCategory::Tls } } diff --git a/core/crates/drivers/mongodb/src/capabilities.rs b/core/crates/drivers/mongodb/src/capabilities.rs index 2acff9271b..0b3cef53c1 100644 --- a/core/crates/drivers/mongodb/src/capabilities.rs +++ b/core/crates/drivers/mongodb/src/capabilities.rs @@ -17,6 +17,8 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { username_required: false, tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + tls_ports: &[], ca_file: true, client_identity: true, // On a direct route the client checks each server it finds under diff --git a/core/crates/drivers/mongodb/src/client_tls.rs b/core/crates/drivers/mongodb/src/client_tls.rs index 847b5fb3f0..c71adbcb91 100644 --- a/core/crates/drivers/mongodb/src/client_tls.rs +++ b/core/crates/drivers/mongodb/src/client_tls.rs @@ -40,7 +40,8 @@ impl ClientTls { let roots = match tls.mode { TlsMode::VerifyFull => Some(tablepro_net::tls::ca_bundle_pem(tls).map_err(crate::endpoint::setup_error)?), TlsMode::Disable | TlsMode::Require => None, - TlsMode::Strict => { + // TLS is a property of the port, so there is nothing to prefer. + TlsMode::Prefer | TlsMode::Strict => { return Err(DriverError::Config(tablepro_core::ConfigError::UnsupportedTlsMode)); } }; diff --git a/core/crates/drivers/mongodb/src/endpoint.rs b/core/crates/drivers/mongodb/src/endpoint.rs index afd304a888..2c35bf439e 100644 --- a/core/crates/drivers/mongodb/src/endpoint.rs +++ b/core/crates/drivers/mongodb/src/endpoint.rs @@ -10,7 +10,8 @@ use mongodb::options::{ClientOptions, Credential, DriverInfo, ServerAddress}; use secrecy::ExposeSecret; use tablepro_core::{ APPLICATION_NAME, ConfigError, ConnectEnvironment, Credentials, DriverError, LivenessPolicy, LossPhase, - NetworkEndpoint, NetworkOptions, NetworkTarget, ServerInfo, TimeoutPhase, TlsFailure, Transport, TransportRoute, + NetworkEndpoint, NetworkOptions, NetworkTarget, ServerInfo, TimeoutPhase, TlsFailure, TlsMode, Transport, + TransportRoute, }; use tablepro_net::tls::TlsSetupError; @@ -62,6 +63,8 @@ pub(crate) struct MongoEndpoint { route: Route, liveness: LivenessPolicy, database: Option, + // A seed list's host is no server, so only one host reached in the clear is asked for TLS. + plaintext_server: Option, } impl MongoEndpoint { @@ -135,6 +138,8 @@ impl MongoEndpoint { Route::Relayed(relay) } }; + let plaintext_server = (!target.options.dns_seed_list && target.tls.mode == TlsMode::Disable) + .then(|| target.tls_server_name().to_owned()); Ok(Self { transport: target.transport.clone(), service, @@ -142,6 +147,7 @@ impl MongoEndpoint { route, liveness, database, + plaintext_server, }) } @@ -184,7 +190,8 @@ impl MongoEndpoint { Ok(Ok(_)) => Ok(client), Ok(Err(error)) => { client.shutdown().immediate(true).await; - Err(self.explain(&error, LossPhase::Connect).await) + let failed = self.explain(&error, LossPhase::Connect).await; + Err(self.refused_in_the_clear(failed).await) } Err(_) => { client.shutdown().immediate(true).await; @@ -200,6 +207,24 @@ impl MongoEndpoint { }) } + // A server that takes only TLS drops a connect in the clear unanswered, which a handshake of its own tells apart. + async fn refused_in_the_clear(&self, failed: DriverError) -> DriverError { + let Some(server_name) = &self.plaintext_server else { + return failed; + }; + if !matches!(failed, DriverError::ConnectionLost { .. }) { + return failed; + } + let within = self.liveness.login_timeout; + if !tablepro_net::tls::serves_tls(self.transport.as_ref(), server_name, within).await { + return failed; + } + DriverError::Tls { + failure: TlsFailure::ServerRequiresTls, + detail: failed.to_string(), + } + } + /// Build the client where the library reads its TLS files, which live /// only until it has. async fn build(&self, mut options: ClientOptions) -> Result { diff --git a/core/crates/drivers/mongodb/tests/integration/tls.rs b/core/crates/drivers/mongodb/tests/integration/tls.rs index 283ec0b981..ea1e9cc2c5 100644 --- a/core/crates/drivers/mongodb/tests/integration/tls.rs +++ b/core/crates/drivers/mongodb/tests/integration/tls.rs @@ -121,9 +121,10 @@ impl TlsConformanceEngine for MongoTlsEngine { } /// The server reads the plaintext hello as a broken handshake and - /// closes the connection without a reply. + /// closes the connection without a reply, then completes the + /// driver's own TLS handshake. fn plaintext_rejection_category(&self) -> ErrorCategory { - ErrorCategory::ConnectionLost + ErrorCategory::Tls } /// The client library checks each server under its own name, so the @@ -258,7 +259,7 @@ impl TlsConformanceEngine for MongoForwardTlsEngine { } fn plaintext_rejection_category(&self) -> ErrorCategory { - ErrorCategory::ConnectionLost + ErrorCategory::Tls } } diff --git a/core/crates/drivers/mssql/src/capabilities.rs b/core/crates/drivers/mssql/src/capabilities.rs index 1c7bf3759a..29dae18570 100644 --- a/core/crates/drivers/mssql/src/capabilities.rs +++ b/core/crates/drivers/mssql/src/capabilities.rs @@ -24,6 +24,8 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { // are not authenticated by one, so there is nothing for it to prove. tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull, TlsMode::Strict], + default_mode: TlsMode::VerifyFull, + tls_ports: &[], ca_file: true, client_identity: false, server_name_override: ServerNameOverride::AnyRoute, diff --git a/core/crates/drivers/mssql/src/login.rs b/core/crates/drivers/mssql/src/login.rs index 25cccea585..98f90cb2d4 100644 --- a/core/crates/drivers/mssql/src/login.rs +++ b/core/crates/drivers/mssql/src/login.rs @@ -132,7 +132,7 @@ impl LoginPlan { ); match self.tls.mode() { TlsMode::Strict => prelogin && !strict, - TlsMode::Disable | TlsMode::Require | TlsMode::VerifyFull => strict && !prelogin, + TlsMode::Disable | TlsMode::Prefer | TlsMode::Require | TlsMode::VerifyFull => strict && !prelogin, } } diff --git a/core/crates/drivers/mssql/src/tls_config.rs b/core/crates/drivers/mssql/src/tls_config.rs index 499b72cb1f..c101ad33ce 100644 --- a/core/crates/drivers/mssql/src/tls_config.rs +++ b/core/crates/drivers/mssql/src/tls_config.rs @@ -52,6 +52,9 @@ pub(crate) struct TlsPlan { impl TlsPlan { pub(crate) fn new(tls: &TlsConfig) -> Result { + if tls.mode == TlsMode::Prefer { + return Err(DriverError::Config(ConfigError::UnsupportedTlsMode)); + } if tls.client_identity.is_some() { return Err(DriverError::Config(ConfigError::ClientIdentityUnsupported)); } @@ -69,7 +72,7 @@ impl TlsPlan { pub(crate) fn apply(&self, config: &mut Config) { match self.mode { TlsMode::Disable => config.encryption(EncryptionLevel::NotSupported), - TlsMode::Require => { + TlsMode::Prefer | TlsMode::Require => { config.encryption(EncryptionLevel::Required); config.trust_cert(); } @@ -139,7 +142,7 @@ impl TlsPlan { fn handshake_failure(&self, failure: TlsFailure) -> TlsFailure { match self.mode { TlsMode::Disable => TlsFailure::ServerRequiresTls, - TlsMode::Require | TlsMode::VerifyFull | TlsMode::Strict => failure, + TlsMode::Prefer | TlsMode::Require | TlsMode::VerifyFull | TlsMode::Strict => failure, } } @@ -149,7 +152,9 @@ impl TlsPlan { pub(crate) fn opening_refused(&self, detail: String) -> DriverError { let failure = match self.mode { TlsMode::Strict => TlsFailure::ServerRefusedStrict, - TlsMode::Disable | TlsMode::Require | TlsMode::VerifyFull => TlsFailure::ServerRequiresStrict, + TlsMode::Disable | TlsMode::Prefer | TlsMode::Require | TlsMode::VerifyFull => { + TlsFailure::ServerRequiresStrict + } }; DriverError::Tls { failure, detail } } diff --git a/core/crates/drivers/mysql/src/capabilities.rs b/core/crates/drivers/mysql/src/capabilities.rs index 6485125053..6a0f2aeb66 100644 --- a/core/crates/drivers/mysql/src/capabilities.rs +++ b/core/crates/drivers/mysql/src/capabilities.rs @@ -16,7 +16,9 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { auth_modes: &[AuthMode::Password], username_required: true, tls: Some(TlsCapabilities { - modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + modes: &[TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Prefer, + tls_ports: &[], ca_file: true, client_identity: true, // sqlx dials and verifies the same `host`, so a name other than @@ -67,7 +69,11 @@ mod tests { assert!(CAPABILITIES.supports(AuthMode::Password)); assert!(!CAPABILITIES.supports(AuthMode::Kerberos)); let tls = CAPABILITIES.tls.expect("MySQL offers TLS"); - assert_eq!(tls.modes.len(), 3); + assert_eq!( + tls.modes, + [TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull] + ); + assert_eq!(tls.default_mode, TlsMode::Prefer); assert!(tls.ca_file && tls.client_identity); assert_eq!(tls.server_name_override, ServerNameOverride::SshForwardOnly); assert_eq!(CAPABILITIES.read_only, ReadOnlyEnforcement::SessionDefault); diff --git a/core/crates/drivers/mysql/src/physical.rs b/core/crates/drivers/mysql/src/physical.rs index 1e6721861a..e527079793 100644 --- a/core/crates/drivers/mysql/src/physical.rs +++ b/core/crates/drivers/mysql/src/physical.rs @@ -321,6 +321,7 @@ fn tls_setup_failed(error: tablepro_net::tls::TlsSetupError, failure: tablepro_c fn ssl_mode(mode: TlsMode) -> Result { match mode { TlsMode::Disable => Ok(MySqlSslMode::Disabled), + TlsMode::Prefer => Ok(MySqlSslMode::Preferred), TlsMode::Require => Ok(MySqlSslMode::Required), TlsMode::VerifyFull => Ok(MySqlSslMode::VerifyIdentity), TlsMode::Strict => Err(DriverError::Config(ConfigError::UnsupportedTlsMode)), @@ -631,4 +632,21 @@ mod tests { "{error:?}" ); } + + #[test] + fn each_mode_asks_sqlx_for_what_the_mysql_client_does() { + let modes = [ + (TlsMode::Disable, MySqlSslMode::Disabled), + (TlsMode::Prefer, MySqlSslMode::Preferred), + (TlsMode::Require, MySqlSslMode::Required), + (TlsMode::VerifyFull, MySqlSslMode::VerifyIdentity), + ]; + for (mode, expected) in modes { + assert!( + matches!(ssl_mode(mode), Ok(asked) if std::mem::discriminant(&asked) == std::mem::discriminant(&expected)), + "{mode:?}" + ); + } + assert!(ssl_mode(TlsMode::Strict).is_err()); + } } diff --git a/core/crates/drivers/mysql/tests/integration/tls.rs b/core/crates/drivers/mysql/tests/integration/tls.rs index f5ec02b712..3ea997b09c 100644 --- a/core/crates/drivers/mysql/tests/integration/tls.rs +++ b/core/crates/drivers/mysql/tests/integration/tls.rs @@ -360,6 +360,52 @@ async fn disabled_against_require_secure_transport() { } } +/// Prefer is sqlx's `Preferred`, as the mysql client's `PREFERRED`: a +/// server without TLS is reached in plaintext, and one with TLS is +/// encrypted with its certificate, which no system root vouches for, +/// left unchecked. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires docker"] +async fn prefer_encrypts_where_the_server_offers_tls_and_connects_where_it_does_not() { + let prefer = TlsConfig { + mode: TlsMode::Prefer, + ..TlsConfig::disabled() + }; + for flavour in FLAVOURS { + let tls_off = match flavour { + MysqlFlavour::Mysql => "--tls-version=", + MysqlFlavour::Mariadb => "--skip-ssl", + }; + let plain = start_with( + MysqlOptions::new(flavour) + .allowing_plaintext() + .with_server_argument(tls_off), + ) + .await; + let with_tls = start_with(MysqlOptions::new(flavour).allowing_plaintext()).await; + for (fixture, encrypted) in [(&plain, false), (&with_tls, true)] { + let liveness = test_liveness(); + let options = options_over( + direct(fixture.host(), fixture.port(), &liveness), + password(&fixture.root_credentials()), + fixture.database(), + prefer.clone(), + WorkspaceSettings::workspace(false), + liveness, + ); + + let connection = MysqlDriver + .connect(options, CancellationToken::new()) + .await + .unwrap_or_else(|error| panic!("{flavour:?}, TLS {encrypted}: {error:?}")); + + let version = ssl_version(connection.as_ref()).await; + assert_eq!(version.starts_with("TLS"), encrypted, "{flavour:?}: {version:?}"); + connection.close().await.expect("a close"); + } + } +} + /// A CA that did not issue the server's certificate is named as such. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires docker"] diff --git a/core/crates/drivers/postgres/src/capabilities.rs b/core/crates/drivers/postgres/src/capabilities.rs index 90645fa913..96fecea23c 100644 --- a/core/crates/drivers/postgres/src/capabilities.rs +++ b/core/crates/drivers/postgres/src/capabilities.rs @@ -16,7 +16,9 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { auth_modes: &[AuthMode::Password], username_required: true, tls: Some(TlsCapabilities { - modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + modes: &[TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Prefer, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, @@ -63,7 +65,11 @@ mod tests { assert!(CAPABILITIES.supports(AuthMode::Password)); assert!(!CAPABILITIES.supports(AuthMode::Kerberos)); let tls = CAPABILITIES.tls.expect("PostgreSQL offers TLS"); - assert_eq!(tls.modes.len(), 3); + assert_eq!( + tls.modes, + [TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull] + ); + assert_eq!(tls.default_mode, TlsMode::Prefer); assert!(tls.ca_file && tls.client_identity); assert_eq!(tls.server_name_override, ServerNameOverride::AnyRoute); assert_eq!(CAPABILITIES.read_only, ReadOnlyEnforcement::SessionDefault); diff --git a/core/crates/drivers/postgres/src/errors.rs b/core/crates/drivers/postgres/src/errors.rs index 45dac95d45..7a90f67d55 100644 --- a/core/crates/drivers/postgres/src/errors.rs +++ b/core/crates/drivers/postgres/src/errors.rs @@ -57,15 +57,15 @@ const INVALID_CATALOG_NAME: &str = "3D000"; pub(crate) fn map_connect_error( error: &tokio_postgres::Error, database: &str, - tls_requested: bool, + tls_required: bool, handshake_started: bool, ) -> DriverError { - connect_error(map_error(error), database, tls_requested, handshake_started) + connect_error(map_error(error), database, tls_required, handshake_started) } -fn connect_error(mapped: DriverError, database: &str, tls_requested: bool, handshake_started: bool) -> DriverError { +fn connect_error(mapped: DriverError, database: &str, tls_required: bool, handshake_started: bool) -> DriverError { match mapped { - DriverError::Tls { detail, .. } if tls_requested && !handshake_started => DriverError::Tls { + DriverError::Tls { detail, .. } if tls_required && !handshake_started => DriverError::Tls { failure: TlsFailure::ServerRefusedTls, detail, }, diff --git a/core/crates/drivers/postgres/src/physical.rs b/core/crates/drivers/postgres/src/physical.rs index 0c77e66e3b..24beaf647b 100644 --- a/core/crates/drivers/postgres/src/physical.rs +++ b/core/crates/drivers/postgres/src/physical.rs @@ -113,7 +113,7 @@ impl PgEndpoint { Ok(Ok(connected)) => Ok(connected), Ok(Err(error)) => { let started = handshake_started.load(Ordering::SeqCst); - let mapped = map_connect_error(&error, self.login_database(), self.tls.requested(), started); + let mapped = map_connect_error(&error, self.login_database(), self.tls.required(), started); Err(self.explain(mapped).await) } } diff --git a/core/crates/drivers/postgres/src/tls.rs b/core/crates/drivers/postgres/src/tls.rs index 662a6b62d9..ded6393081 100644 --- a/core/crates/drivers/postgres/src/tls.rs +++ b/core/crates/drivers/postgres/src/tls.rs @@ -4,7 +4,7 @@ use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use tablepro_core::{DriverError, TlsConfig, TlsFailure}; +use tablepro_core::{DriverError, TlsConfig, TlsFailure, TlsMode}; use tablepro_net::tls::{TlsSetupError, build_client_config}; use tokio_postgres::config::SslMode; use tokio_postgres::tls::{MakeTlsConnect, TlsConnect}; @@ -22,6 +22,7 @@ type RustlsConnect = >::TlsConn #[derive(Clone)] pub(crate) struct PgTlsSetup { connector: Option, + mode: TlsMode, server_name: String, } @@ -30,19 +31,23 @@ impl PgTlsSetup { let config = build_client_config(tls).map_err(setup_error)?; Ok(Self { connector: config.map(|config| MakeRustlsConnect::new((*config).clone())), + mode: tls.mode, server_name: server_name.to_owned(), }) } pub(crate) fn ssl_mode(&self) -> SslMode { - match self.connector { - Some(_) => SslMode::Require, - None => SslMode::Disable, + match (&self.connector, self.mode) { + (None, _) => SslMode::Disable, + (Some(_), TlsMode::Prefer) => SslMode::Prefer, + (Some(_), _) => SslMode::Require, } } - pub(crate) fn requested(&self) -> bool { - self.connector.is_some() + /// Whether a server that answers the SSLRequest with 'N' fails the + /// connect. Prefer goes on in the clear, as libpq's `prefer` does. + pub(crate) fn required(&self) -> bool { + self.connector.is_some() && self.mode.requires_tls() } /// A connector for one physical connection, and the flag it raises @@ -115,7 +120,19 @@ mod tests { let setup = PgTlsSetup::new(&TlsConfig::disabled(), "db.example.com").expect("a setup"); assert!(matches!(setup.ssl_mode(), SslMode::Disable)); - assert!(!setup.requested()); + assert!(!setup.required()); + } + + #[test] + fn a_preferred_setup_asks_for_tls_and_takes_a_refusal() { + let tls = TlsConfig { + mode: TlsMode::Prefer, + ..TlsConfig::disabled() + }; + let setup = PgTlsSetup::new(&tls, "db.example.com").expect("a setup"); + + assert!(matches!(setup.ssl_mode(), SslMode::Prefer)); + assert!(!setup.required()); } #[test] @@ -149,7 +166,7 @@ mod tests { #[test] fn a_required_setup_asks_for_tls_and_records_nothing_until_used() { let tls = TlsConfig { - mode: tablepro_core::TlsMode::Require, + mode: TlsMode::Require, ..TlsConfig::disabled() }; let setup = PgTlsSetup::new(&tls, "db.example.com").expect("a setup"); @@ -157,6 +174,7 @@ mod tests { let (_connector, started) = setup.connector(); assert!(matches!(setup.ssl_mode(), SslMode::Require)); + assert!(setup.required()); assert!(!started.load(Ordering::SeqCst)); } } diff --git a/core/crates/drivers/postgres/tests/integration/tls.rs b/core/crates/drivers/postgres/tests/integration/tls.rs index a7491c643b..a2e2b34e39 100644 --- a/core/crates/drivers/postgres/tests/integration/tls.rs +++ b/core/crates/drivers/postgres/tests/integration/tls.rs @@ -163,6 +163,56 @@ async fn server_without_ssl_reports_server_refused_tls() { ); } +fn prefer() -> TlsConfig { + TlsConfig { + mode: TlsMode::Prefer, + ..TlsConfig::disabled() + } +} + +/// Prefer goes on in plaintext after the server answers 'N', as libpq's +/// `prefer` does: a new connection to a local server without TLS works. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires docker"] +async fn prefer_connects_to_a_server_without_ssl() { + let fixture = start().await; + let liveness = test_liveness(); + let options = options_over( + direct(fixture.host(), fixture.port(), &liveness), + password(&fixture.password_credentials()), + fixture.database(), + prefer(), + WorkspaceSettings::workspace(false), + liveness, + ); + + let outcome = PgDriver.connect(options, CancellationToken::new()).await; + + assert!(outcome.is_ok(), "got {:?}", outcome.err()); +} + +/// The server takes only TLS logins, and its certificate comes from a CA +/// the system does not trust, so a login under Prefer proves it encrypted +/// without checking the certificate. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires docker"] +async fn prefer_encrypts_where_the_server_offers_tls_and_checks_no_certificate() { + let fixture = start_with_pki(PkiAlgorithm::RsaSha256).await; + let liveness = test_liveness(); + let options = options_over( + direct(fixture.host(), fixture.port(), &liveness), + password(&fixture.password_credentials()), + fixture.database(), + prefer(), + WorkspaceSettings::workspace(false), + liveness, + ); + + let outcome = PgDriver.connect(options, CancellationToken::new()).await; + + assert!(outcome.is_ok(), "got {:?}", outcome.err()); +} + /// pg_hba.conf turns a plaintext login away with SQLSTATE 28000, a rule /// of the server's that no other password gets past. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/core/crates/drivers/redis/src/capabilities.rs b/core/crates/drivers/redis/src/capabilities.rs index 5dabe0cbdf..8a8a7c4d64 100644 --- a/core/crates/drivers/redis/src/capabilities.rs +++ b/core/crates/drivers/redis/src/capabilities.rs @@ -17,6 +17,8 @@ pub(crate) static CAPABILITIES: DriverCapabilities = DriverCapabilities { username_required: false, tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, diff --git a/core/crates/drivers/redis/src/endpoint.rs b/core/crates/drivers/redis/src/endpoint.rs index 0a7fc3256b..bd4ff31feb 100644 --- a/core/crates/drivers/redis/src/endpoint.rs +++ b/core/crates/drivers/redis/src/endpoint.rs @@ -1,5 +1,6 @@ use std::io; use std::sync::Arc; +use std::time::Duration; use redis::aio::MultiplexedConnection; use redis::{AsyncConnectionConfig, RedisConnectionInfo, Value}; @@ -10,6 +11,7 @@ use tablepro_core::{ NetworkTarget, ServerInfo, TimeoutPhase, TlsFailure, Transport, TransportError, TransportStream, }; use tablepro_net::tls::{TlsSetupError, build_client_config}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_rustls::TlsConnector; use crate::errors::{map_error, server_error}; @@ -23,6 +25,7 @@ use crate::tls_watch::{TlsFailureSlot, TlsWatch}; pub(crate) struct RedisEndpoint { transport: Arc, tls: Option, + tls_server_name: String, login: RedisConnectionInfo, liveness: LivenessPolicy, } @@ -54,6 +57,7 @@ impl RedisEndpoint { Ok(Self { transport: target.transport.clone(), tls, + tls_server_name: target.tls_server_name().to_owned(), login, liveness, }) @@ -72,10 +76,25 @@ impl RedisEndpoint { (Err(DriverError::ConnectionLost { .. }), Some((failure, detail))) => { Err(DriverError::Tls { failure, detail }) } + (Err(lost @ DriverError::ConnectionLost { .. }), None) if self.tls.is_none() => { + Err(self.refused_in_the_clear(lost).await) + } (opened, _) => opened, } } + // A server that takes only TLS drops a login in the clear unanswered, which a handshake of its own tells apart. + async fn refused_in_the_clear(&self, lost: DriverError) -> DriverError { + let within = self.liveness.login_timeout; + if !tablepro_net::tls::serves_tls(self.transport.as_ref(), &self.tls_server_name, within).await { + return lost; + } + DriverError::Tls { + failure: TlsFailure::ServerRequiresTls, + detail: lost.to_string(), + } + } + async fn login(&self, slot: &TlsFailureSlot) -> Result { let stream = self.stream(slot).await?; let config = AsyncConnectionConfig::new() @@ -148,9 +167,16 @@ impl RedisEndpoint { }; let handshake = tls.connector.connect(tls.server_name.clone(), stream); match tokio::time::timeout(bound, handshake).await { - Err(_) => Err(DriverError::Timeout { - phase: TimeoutPhase::Connect, - server_cancelled: false, + // A server without TLS reads the hello as a command and waits for its newline. + Err(_) => Err(match answers_in_the_clear(self.transport.as_ref(), bound).await { + true => DriverError::Tls { + failure: TlsFailure::ServerRefusedTls, + detail: "the server answered a plain PING".to_owned(), + }, + false => DriverError::Timeout { + phase: TimeoutPhase::Connect, + server_cancelled: false, + }, }), Ok(Err(error)) => Err(self.explain(handshake_error(&error)).await), Ok(Ok(stream)) => Ok(Box::new(TlsWatch::new(stream, slot.clone()))), @@ -197,6 +223,19 @@ async fn identify(link: &Link) -> Result, DriverError> { }) } +/// Whether the server answers a plain `PING` with a RESP reply, on a +/// stream of its own that carries nothing else. +async fn answers_in_the_clear(transport: &dyn Transport, within: Duration) -> bool { + let asking = async { + let mut stream = transport.open().await.ok()?; + stream.write_all(b"PING\r\n").await.ok()?; + let mut first = [0_u8; 1]; + stream.read_exact(&mut first).await.ok()?; + Some(matches!(first[0], b'+' | b'-')) + }; + matches!(tokio::time::timeout(within, asking).await, Ok(Some(true))) +} + fn handshake_error(error: &io::Error) -> DriverError { match tablepro_net::tls::classify(error) { Some((failure, detail)) => DriverError::Tls { failure, detail }, diff --git a/core/crates/drivers/redis/tests/integration/tls.rs b/core/crates/drivers/redis/tests/integration/tls.rs index 4ab31a97ae..1f14cf8779 100644 --- a/core/crates/drivers/redis/tests/integration/tls.rs +++ b/core/crates/drivers/redis/tests/integration/tls.rs @@ -6,13 +6,15 @@ use std::sync::Arc; use secrecy::SecretString; use tablepro_core::{ - ClientIdentity, ConnectOptions, Credentials, DatabaseDriver, ErrorCategory, TlsConfig, WorkspaceSettings, + ClientIdentity, ConnectOptions, Credentials, DatabaseDriver, DriverError, ErrorCategory, TlsConfig, TlsFailure, + TlsMode, WorkspaceSettings, }; use tablepro_driver_redis::RedisDriver; use tablepro_test_fixtures::{PkiFile, RedisFixture, TestPki}; use tablepro_test_support::conformance::{ ClientIdentityEngine, ConformanceFailure, TlsConformanceEngine, test_liveness, }; +use tokio_util::sync::CancellationToken; use crate::support::{direct, options_over, password}; @@ -90,9 +92,10 @@ impl TlsConformanceEngine for RedisTlsEngine { } /// The server reads the plaintext login as a broken handshake and - /// closes the connection without a reply. + /// closes the connection without a reply, then completes the + /// driver's own TLS handshake. fn plaintext_rejection_category(&self) -> ErrorCategory { - ErrorCategory::ConnectionLost + ErrorCategory::Tls } } @@ -116,6 +119,40 @@ impl ClientIdentityEngine for RedisTlsEngine { } } +/// A plain Redis reads the TLS hello as a command and waits for its +/// newline, so the handshake times out; a plain PING tells why. +#[tokio::test] +#[ignore = "requires docker"] +async fn require_against_a_server_without_tls_is_refused_tls() { + let fixture = crate::support::start().await; + let liveness = test_liveness(); + let options = options_over( + direct(fixture.host(), fixture.port(), &liveness), + password(&fixture.password_credentials()), + None, + TlsConfig { + mode: TlsMode::Require, + ..TlsConfig::disabled() + }, + WorkspaceSettings::workspace(false), + liveness, + ); + + let outcome = RedisDriver.connect(options, CancellationToken::new()).await; + + assert!( + matches!( + outcome, + Err(DriverError::Tls { + failure: TlsFailure::ServerRefusedTls, + .. + }) + ), + "{:?}", + outcome.err() + ); +} + mod suite { use super::RedisTlsEngine; diff --git a/core/crates/ffi/src/connection_url.rs b/core/crates/ffi/src/connection_url.rs index ff3563b43a..f8bafe28c3 100644 --- a/core/crates/ffi/src/connection_url.rs +++ b/core/crates/ffi/src/connection_url.rs @@ -2,7 +2,7 @@ use std::path::Path; use secrecy::ExposeSecret; use tablepro_core::connection_url::{self, ConnectionUrl}; -use tablepro_core::{TlsMode, is_local_socket_host}; +use tablepro_core::is_local_socket_host; use crate::error::CoreError; use crate::library::TlsModeTag; @@ -36,12 +36,7 @@ pub fn parse_connection_url(url: String) -> Result| path.map(|path| path.display().to_string()); Ok(ParsedConnectionUrl { driver_id: parsed.driver_id.to_owned(), - tls_mode: tls.mode.map(|mode| match mode { - TlsMode::Disable => TlsModeTag::Disable, - TlsMode::Require => TlsModeTag::Require, - TlsMode::VerifyFull => TlsModeTag::VerifyFull, - TlsMode::Strict => TlsModeTag::Strict, - }), + tls_mode: tls.mode.map(TlsModeTag::from), ca_file: path(tls.ca_file.as_deref()), client_certificate: path(tls.client_certificate.as_deref()), client_key: path(tls.client_key.as_deref()), @@ -126,6 +121,10 @@ mod tests { parse("postgresql://db/x?sslmode=disable").tls_mode, Some(TlsModeTag::Disable) ); + assert_eq!( + parse("postgresql://db/x?sslmode=prefer").tls_mode, + Some(TlsModeTag::Prefer) + ); } #[test] diff --git a/core/crates/ffi/src/drivers.rs b/core/crates/ffi/src/drivers.rs index 5aed627af2..fe4d71a28e 100644 --- a/core/crates/ffi/src/drivers.rs +++ b/core/crates/ffi/src/drivers.rs @@ -1,4 +1,7 @@ -use tablepro_core::{AuthMode, DataModel, DatabaseDriver, DriverRegistry, EndpointKind, EngineCategory, TlsMode}; +use tablepro_core::{ + AuthMode, DataModel, DatabaseDriver, DriverRegistry, EndpointKind, EngineCategory, NetworkOptions, + ServerNameOverride, +}; use crate::library::TlsModeTag; @@ -34,10 +37,23 @@ pub struct DriverInfo { pub category: EngineCategoryTag, pub endpoint: EndpointInfo, pub supported_tls_modes: Vec, + // What a new connection starts on (core/docs/decisions/0014-tls-mode-of-a-new-connection.md). + pub default_tls_mode: TlsModeTag, + // Ports where a new connection starts on VerifyFull instead. + pub tls_ports: Vec, + pub server_name_override: ServerNameOverrideTag, pub supports_integrated_auth: bool, pub supports_client_identity: bool, } +/// Where the certificate can be checked against a name other than the host. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ServerNameOverrideTag { + AnyRoute, + SshForwardOnly, + Unsupported, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] pub enum DataModelTag { Relational, @@ -92,17 +108,18 @@ impl DriverInfo { DataModel::Document => DataModelTag::Document, }, category: driver.category().into(), - supported_tls_modes: capabilities.tls.map_or_else(Vec::new, |tls| { - tls.modes - .iter() - .map(|mode| match mode { - TlsMode::Disable => TlsModeTag::Disable, - TlsMode::Require => TlsModeTag::Require, - TlsMode::VerifyFull => TlsModeTag::VerifyFull, - TlsMode::Strict => TlsModeTag::Strict, - }) - .collect() - }), + supported_tls_modes: capabilities + .tls + .map_or_else(Vec::new, |tls| tls.modes.iter().map(|mode| (*mode).into()).collect()), + default_tls_mode: capabilities + .new_connection_tls(capabilities.default_port().unwrap_or(0), &NetworkOptions::default()) + .into(), + tls_ports: capabilities.tls.map_or_else(Vec::new, |tls| tls.tls_ports.to_vec()), + server_name_override: match capabilities.tls.map(|tls| tls.server_name_override) { + Some(ServerNameOverride::AnyRoute) => ServerNameOverrideTag::AnyRoute, + Some(ServerNameOverride::SshForwardOnly) => ServerNameOverrideTag::SshForwardOnly, + Some(ServerNameOverride::Unsupported) | None => ServerNameOverrideTag::Unsupported, + }, supports_integrated_auth: capabilities.supports(AuthMode::Kerberos), supports_client_identity: capabilities.tls.is_some_and(|tls| tls.client_identity), endpoint: match &capabilities.endpoint { @@ -183,6 +200,62 @@ mod tests { ); } + #[test] + fn a_new_connection_starts_on_the_mode_the_engines_own_client_starts_on() { + let expected = [ + ("cassandra", TlsModeTag::Disable), + ("clickhouse", TlsModeTag::Disable), + ("duckdb", TlsModeTag::Disable), + ("mongodb", TlsModeTag::Disable), + ("mssql", TlsModeTag::VerifyFull), + ("mysql", TlsModeTag::Prefer), + ("postgres", TlsModeTag::Prefer), + ("redis", TlsModeTag::Disable), + ("sqlite", TlsModeTag::Disable), + ]; + for driver in registry().iter() { + let info = DriverInfo::of(driver.as_ref()); + let wanted = expected.iter().find(|(id, _)| *id == info.id).map(|(_, mode)| *mode); + assert_eq!(Some(info.default_tls_mode), wanted, "{}", info.id); + assert!( + info.supported_tls_modes.is_empty() || info.supported_tls_modes.contains(&info.default_tls_mode), + "{}", + info.id + ); + assert_eq!( + info.supported_tls_modes.contains(&TlsModeTag::Prefer), + matches!(info.id.as_str(), "mysql" | "postgres"), + "{}", + info.id + ); + assert!( + info.tls_ports.is_empty() || info.supported_tls_modes.contains(&TlsModeTag::VerifyFull), + "{}", + info.id + ); + } + } + + #[test] + fn the_form_learns_where_a_server_name_can_be_checked() { + fn tag(driver: &dyn DatabaseDriver) -> ServerNameOverrideTag { + DriverInfo::of(driver).server_name_override + } + + assert_eq!( + tag(&tablepro_driver_postgres::PgDriver), + ServerNameOverrideTag::AnyRoute + ); + assert_eq!( + tag(&tablepro_driver_mysql::MysqlDriver), + ServerNameOverrideTag::SshForwardOnly + ); + assert_eq!( + tag(&tablepro_driver_sqlite::SqliteDriver), + ServerNameOverrideTag::Unsupported + ); + } + #[test] fn a_file_engine_lists_its_suffixes() { let sqlite = DriverInfo::of(&tablepro_driver_sqlite::SqliteDriver); diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index d7c6b19e63..57a6ba76c2 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -26,7 +26,7 @@ pub use catalog::{ColumnEntry, ObjectEntry, ObjectKindTag, ObjectScopeArg, Schem pub use cloud::{CloudConnectionFields, CloudGroupFields, CloudLibraryPull, CloudLibraryRecords}; pub use connection_url::{ParsedConnectionUrl, parse_connection_url}; pub use core_handle::{Core, FileOpenRequest}; -pub use drivers::{DataModelTag, DriverInfo, EndpointInfo, EngineCategoryTag}; +pub use drivers::{DataModelTag, DriverInfo, EndpointInfo, EngineCategoryTag, ServerNameOverrideTag}; pub use editor::{QueryEditor, RunSettings}; pub use error::{BoxedErrorInfo, CoreError, ErrorInfo, HostKeyFailure, ServerMessage, TlsFailureTag}; pub use host::{HostConfig, HostSecretError, HostSecretStore, HostSecrets, SecretItemTag, SecretKindTag}; diff --git a/core/crates/ffi/src/library.rs b/core/crates/ffi/src/library.rs index 245313d5f6..462b4b5ab1 100644 --- a/core/crates/ffi/src/library.rs +++ b/core/crates/ffi/src/library.rs @@ -18,11 +18,36 @@ use crate::runtime::on_runtime; #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] pub enum TlsModeTag { Disable, + Prefer, Require, VerifyFull, Strict, } +impl From for TlsModeTag { + fn from(mode: TlsMode) -> Self { + match mode { + TlsMode::Disable => Self::Disable, + TlsMode::Prefer => Self::Prefer, + TlsMode::Require => Self::Require, + TlsMode::VerifyFull => Self::VerifyFull, + TlsMode::Strict => Self::Strict, + } + } +} + +impl From for TlsMode { + fn from(tag: TlsModeTag) -> Self { + match tag { + TlsModeTag::Disable => Self::Disable, + TlsModeTag::Prefer => Self::Prefer, + TlsModeTag::Require => Self::Require, + TlsModeTag::VerifyFull => Self::VerifyFull, + TlsModeTag::Strict => Self::Strict, + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] pub enum SafeModeTag { Off, @@ -535,16 +560,8 @@ fn path(text: Option<&String>) -> Option { } fn tls_config(settings: &TlsSettings) -> TlsConfig { - let mut config = match settings.mode { - TlsModeTag::Disable => TlsConfig::disabled(), - TlsModeTag::Require | TlsModeTag::VerifyFull | TlsModeTag::Strict => TlsConfig::verify_full(), - }; - config.mode = match settings.mode { - TlsModeTag::Disable => TlsMode::Disable, - TlsModeTag::Require => TlsMode::Require, - TlsModeTag::VerifyFull => TlsMode::VerifyFull, - TlsModeTag::Strict => TlsMode::Strict, - }; + let mut config = TlsConfig::disabled(); + config.mode = settings.mode.into(); config.ca_file = path(settings.ca_file.as_ref()); config.client_identity = match ( path(settings.client_certificate.as_ref()), @@ -607,12 +624,7 @@ impl From<&SavedConnection> for ConnectionRecord { username: saved.username.clone(), integrated_auth: saved.auth_mode == AuthMode::Kerberos, tls: TlsSettings { - mode: match saved.tls.mode { - TlsMode::Disable => TlsModeTag::Disable, - TlsMode::Require => TlsModeTag::Require, - TlsMode::VerifyFull => TlsModeTag::VerifyFull, - TlsMode::Strict => TlsModeTag::Strict, - }, + mode: saved.tls.mode.into(), ca_file: saved.tls.ca_file.as_deref().map(shown), client_certificate: saved .tls diff --git a/core/crates/foreign-import/src/review/mapping.rs b/core/crates/foreign-import/src/review/mapping.rs index baffb54931..9de3795a59 100644 --- a/core/crates/foreign-import/src/review/mapping.rs +++ b/core/crates/foreign-import/src/review/mapping.rs @@ -37,8 +37,6 @@ const DRIVER_IDS: &[(&str, &str)] = &[ ("MongoDB", "mongodb"), ]; -const TLS_STRENGTH: [TlsMode; 3] = [TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull]; - #[derive(Debug, Clone)] pub struct ImportedSecret { pub kind: SecretKind, @@ -225,13 +223,20 @@ fn color(color: ForeignColor) -> ConnectionColor { fn natural_mode(mode: ForeignSslMode) -> TlsMode { match mode { ForeignSslMode::Disabled => TlsMode::Disable, - ForeignSslMode::Preferred | ForeignSslMode::Required => TlsMode::Require, + ForeignSslMode::Preferred => TlsMode::Prefer, + ForeignSslMode::Required => TlsMode::Require, ForeignSslMode::VerifyCa | ForeignSslMode::VerifyIdentity => TlsMode::VerifyFull, } } -fn strength(mode: TlsMode) -> usize { - TLS_STRENGTH.iter().position(|known| *known == mode).unwrap_or(0) +fn strength(mode: TlsMode) -> u8 { + match mode { + TlsMode::Disable => 0, + TlsMode::Prefer => 1, + TlsMode::Require => 2, + TlsMode::VerifyFull => 3, + TlsMode::Strict => 4, + } } // The weakest mode at least as strong as the one wanted, or the strongest below it when none is. @@ -272,7 +277,7 @@ fn map_tls( } return TlsConfig::disabled(); }; - if mode != wanted || matches!(from, ForeignSslMode::Preferred | ForeignSslMode::VerifyCa) { + if mode != wanted || from == ForeignSslMode::VerifyCa { notes.push(RowNote::TlsModeChanged { from, to: mode }); } let mut config = TlsConfig { diff --git a/core/crates/foreign-import/tests/review.rs b/core/crates/foreign-import/tests/review.rs index b4db870be4..8c012842a4 100644 --- a/core/crates/foreign-import/tests/review.rs +++ b/core/crates/foreign-import/tests/review.rs @@ -34,6 +34,8 @@ const ALL_MODES: &[TlsMode] = &[TlsMode::Disable, TlsMode::Require, TlsMode::Ver const FULL_TLS: TlsCapabilities = TlsCapabilities { modes: ALL_MODES, + default_mode: TlsMode::Disable, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, @@ -77,7 +79,15 @@ const fn file(suffix: &'static [&'static str]) -> DriverCapabilities { } static MYSQL: DriverCapabilities = network(3306, DataModel::Relational, Some(FULL_TLS)); -static POSTGRES: DriverCapabilities = network(5432, DataModel::Relational, Some(FULL_TLS)); +static POSTGRES: DriverCapabilities = network( + 5432, + DataModel::Relational, + Some(TlsCapabilities { + modes: &[TlsMode::Disable, TlsMode::Prefer, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::Prefer, + ..FULL_TLS + }), +); static MSSQL: DriverCapabilities = network( 1433, DataModel::Relational, @@ -100,6 +110,7 @@ static VERIFY_ONLY: DriverCapabilities = network( DataModel::Relational, Some(TlsCapabilities { modes: &[TlsMode::VerifyFull], + default_mode: TlsMode::VerifyFull, ca_file: false, ..FULL_TLS }), @@ -838,7 +849,7 @@ fn each_tls_mode_maps_to_the_core_mode_and_a_change_is_noted() { let cases = [ (None, TlsMode::Disable, false), (Some(ForeignSslMode::Disabled), TlsMode::Disable, false), - (Some(ForeignSslMode::Preferred), TlsMode::Require, true), + (Some(ForeignSslMode::Preferred), TlsMode::Prefer, false), (Some(ForeignSslMode::Required), TlsMode::Require, false), (Some(ForeignSslMode::VerifyCa), TlsMode::VerifyFull, true), (Some(ForeignSslMode::VerifyIdentity), TlsMode::VerifyFull, false), @@ -865,6 +876,7 @@ fn a_mode_the_driver_lacks_becomes_the_nearest_it_has_and_never_weaker_when_a_st (&VERIFY_ONLY, ForeignSslMode::Required, TlsMode::VerifyFull), (&VERIFY_ONLY, ForeignSslMode::Disabled, TlsMode::VerifyFull), (&NO_VERIFY, ForeignSslMode::VerifyIdentity, TlsMode::Require), + (&REDIS, ForeignSslMode::Preferred, TlsMode::Require), ]; for (capabilities, from, to) in cases { let row = review_with( @@ -1943,20 +1955,14 @@ fn tls_the_other_app_used_with_its_ssl_setting_off_is_noted_and_keeps_the_row_ch let preferred = only_row(defaulted(ForeignSslMode::Preferred)); assert_eq!( preferred.notes, - [ - RowNote::TlsFromDriverDefault { - mode: ForeignSslMode::Preferred - }, - RowNote::TlsModeChanged { - from: ForeignSslMode::Preferred, - to: TlsMode::Require - }, - ] + [RowNote::TlsFromDriverDefault { + mode: ForeignSslMode::Preferred + }] ); assert!(preferred.selected_by_default); assert_eq!( preferred.connection.expect("a supported engine").tls.mode, - TlsMode::Require + TlsMode::Prefer ); let verified = only_row(defaulted(ForeignSslMode::VerifyIdentity)); diff --git a/core/crates/net/Cargo.toml b/core/crates/net/Cargo.toml index a059175a66..16b18dd6c1 100644 --- a/core/crates/net/Cargo.toml +++ b/core/crates/net/Cargo.toml @@ -17,6 +17,7 @@ socket2.workspace = true tempfile.workspace = true thiserror.workspace = true tokio = { workspace = true, features = ["net", "rt"] } +tokio-rustls.workspace = true tracing.workspace = true [target.'cfg(unix)'.dependencies] @@ -31,7 +32,6 @@ hyper-rustls.workspace = true hyper-util.workspace = true rcgen.workspace = true tokio = { workspace = true, features = ["io-util"] } -tokio-rustls.workspace = true tower-service.workspace = true [lints] diff --git a/core/crates/net/src/tls/client_config.rs b/core/crates/net/src/tls/client_config.rs index 952b5ab205..90f46adc75 100644 --- a/core/crates/net/src/tls/client_config.rs +++ b/core/crates/net/src/tls/client_config.rs @@ -54,7 +54,7 @@ fn verifier( ) -> Result>, TlsSetupError> { Ok(Some(match tls.mode { TlsMode::Disable => return Ok(None), - TlsMode::Require => Arc::new(UnverifiedServerCertVerifier::new(Arc::clone(provider))), + TlsMode::Prefer | TlsMode::Require => Arc::new(UnverifiedServerCertVerifier::new(Arc::clone(provider))), TlsMode::VerifyFull | TlsMode::Strict => { let extra_roots = match &tls.ca_file { Some(path) => read_certificates(path)?, diff --git a/core/crates/net/src/tls/mod.rs b/core/crates/net/src/tls/mod.rs index f07f5c4046..2034e3e1b9 100644 --- a/core/crates/net/src/tls/mod.rs +++ b/core/crates/net/src/tls/mod.rs @@ -4,6 +4,7 @@ mod client_config; mod fixed_name; mod off_runtime; mod pem_check; +mod probe; mod setup_error; mod unverified; @@ -13,5 +14,6 @@ pub use client_config::{build_client_config, build_client_config_checking}; pub use fixed_name::FixedNameVerifier; pub use off_runtime::set_up_off_runtime; pub use pem_check::{MAX_PEM_FILE_BYTES, check_pem_files}; +pub use probe::serves_tls; pub use setup_error::TlsSetupError; pub use unverified::UnverifiedServerCertVerifier; diff --git a/core/crates/net/src/tls/probe.rs b/core/crates/net/src/tls/probe.rs new file mode 100644 index 0000000000..ad0e0e3b7f --- /dev/null +++ b/core/crates/net/src/tls/probe.rs @@ -0,0 +1,149 @@ +use std::time::Duration; + +use rustls_pki_types::ServerName; +use tablepro_core::{TlsConfig, TlsMode, Transport}; +use tokio_rustls::TlsConnector; + +use crate::tls::build_client_config; + +// The certificate goes unchecked because nothing is sent past the handshake, so no credential can reach the server. +pub async fn serves_tls(transport: &dyn Transport, server_name: &str, within: Duration) -> bool { + let unchecked = TlsConfig { + mode: TlsMode::Require, + ..TlsConfig::disabled() + }; + let Ok(Some(config)) = build_client_config(&unchecked) else { + return false; + }; + let Ok(name) = ServerName::try_from(server_name.to_owned()) else { + return false; + }; + let connector = TlsConnector::from(config); + let probing = async { + let stream = transport.open().await.ok()?; + connector.connect(name, stream).await.ok() + }; + matches!(tokio::time::timeout(within, probing).await, Ok(Some(_))) +} + +#[cfg(test)] +mod tests { + use std::net::SocketAddr; + use std::sync::Arc; + + use rcgen::{CertificateParams, KeyPair}; + use rustls::ServerConfig; + use rustls_pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; + use tablepro_core::{LivenessPolicy, NetworkEndpoint}; + use tokio::io::AsyncReadExt; + use tokio::net::TcpListener; + use tokio::task::JoinHandle; + use tokio_rustls::TlsAcceptor; + + use super::*; + use crate::DirectTcpTransport; + + const NAME: &str = "db.internal"; + const WITHIN: Duration = Duration::from_secs(5); + + #[derive(Debug, Clone, Copy)] + enum Plain { + HangUp, + Echo, + Silent, + } + + fn transport(address: SocketAddr) -> DirectTcpTransport { + let endpoint = NetworkEndpoint::new("127.0.0.1", address.port()).unwrap(); + DirectTcpTransport::new(endpoint, &LivenessPolicy::DESKTOP) + } + + fn server_config() -> Arc { + let key = KeyPair::generate().unwrap(); + let certificate = CertificateParams::new(vec![NAME.to_owned()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())); + let mut config = ServerConfig::builder_with_provider(Arc::new(rustls::crypto::aws_lc_rs::default_provider())) + .with_protocol_versions(rustls::DEFAULT_VERSIONS) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certificate.der().clone()], key) + .unwrap(); + // A ticket written after the probe has closed its stream could fail the accept. + config.send_tls13_tickets = 0; + Arc::new(config) + } + + // Returns what the client sent after the handshake. + async fn tls_server() -> (SocketAddr, JoinHandle>>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let acceptor = TlsAcceptor::from(server_config()); + let serving = tokio::spawn(async move { + let (stream, _) = listener.accept().await.ok()?; + let mut tls = acceptor.accept(stream).await.ok()?; + let mut sent = Vec::new(); + let _ = tls.read_to_end(&mut sent).await; + Some(sent) + }); + (address, serving) + } + + async fn plain_server(plain: Plain) -> SocketAddr { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + match plain { + Plain::HangUp => { + let mut hello = [0u8; 1]; + let _ = stream.read(&mut hello).await; + } + Plain::Echo => { + let (mut reading, mut writing) = stream.split(); + let _ = tokio::io::copy(&mut reading, &mut writing).await; + } + // Redis without TLS reads the hello as a command and waits for its newline. + Plain::Silent => { + let mut hello = [0u8; 1]; + let _ = stream.read(&mut hello).await; + std::future::pending::<()>().await; + } + } + }); + address + } + + #[tokio::test] + async fn a_tls_server_serves_tls_and_is_sent_nothing_past_the_handshake() { + let (address, serving) = tls_server().await; + + assert!(serves_tls(&transport(address), NAME, WITHIN).await); + assert_eq!(serving.await.unwrap(), Some(Vec::new())); + } + + #[tokio::test] + async fn a_plain_server_does_not_serve_tls() { + for plain in [Plain::HangUp, Plain::Echo, Plain::Silent] { + let address = plain_server(plain).await; + + assert!( + !serves_tls(&transport(address), NAME, Duration::from_millis(500)).await, + "{plain:?}" + ); + } + } + + #[tokio::test] + async fn nothing_listening_does_not_serve_tls() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + + assert!(!serves_tls(&transport(address), NAME, WITHIN).await); + } +} diff --git a/core/crates/session/src/connect/driver_connector.rs b/core/crates/session/src/connect/driver_connector.rs index bcc3c21b21..b5ec8a626b 100644 --- a/core/crates/session/src/connect/driver_connector.rs +++ b/core/crates/session/src/connect/driver_connector.rs @@ -407,6 +407,8 @@ mod tests { const SOCKET_WITH_TLS: DriverCapabilities = DriverCapabilities { tls: Some(tablepro_core::TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::VerifyFull], + default_mode: TlsMode::Disable, + tls_ports: &[], ca_file: false, client_identity: false, server_name_override: tablepro_core::ServerNameOverride::Unsupported, diff --git a/core/crates/test-support/src/conformance/cases/tls.rs b/core/crates/test-support/src/conformance/cases/tls.rs index e8ab10fc95..60acd06341 100644 --- a/core/crates/test-support/src/conformance/cases/tls.rs +++ b/core/crates/test-support/src/conformance/cases/tls.rs @@ -138,9 +138,19 @@ pub async fn disable_against_tls_only_server_is_refused ) -> Result<(), ConformanceFailure> { let expected = engine.plaintext_rejection_category(); let outcome = open::(DISABLE_CASE, engine.connect_options(TlsConfig::disabled())).await?; - let refused = matches!(&outcome, Err(error) if error.category() == expected); + // Of the TLS failures, only this one tells the app that turning TLS on fixes the connect. + let (refused, wanted) = match expected { + ErrorCategory::Tls => ( + tls_failure(&outcome) == Some(TlsFailure::ServerRequiresTls), + format!("{:?}", TlsFailure::ServerRequiresTls), + ), + _ => ( + matches!(&outcome, Err(error) if error.category() == expected), + format!("{expected:?}"), + ), + }; expect(DISABLE_CASE, refused, || { - format!("a plaintext connect gave {}, not {expected:?}", describe(&outcome)) + format!("a plaintext connect gave {}, not {wanted}", describe(&outcome)) }) } diff --git a/core/crates/test-support/src/fake_driver.rs b/core/crates/test-support/src/fake_driver.rs index f73268282f..32edde1bfd 100644 --- a/core/crates/test-support/src/fake_driver.rs +++ b/core/crates/test-support/src/fake_driver.rs @@ -35,6 +35,8 @@ impl FakeDriver { username_required: true, tls: Some(TlsCapabilities { modes: &[TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull], + default_mode: TlsMode::VerifyFull, + tls_ports: &[], ca_file: true, client_identity: true, server_name_override: ServerNameOverride::AnyRoute, diff --git a/core/docs/decisions/0014-tls-mode-of-a-new-connection.md b/core/docs/decisions/0014-tls-mode-of-a-new-connection.md new file mode 100644 index 0000000000..292389b02e --- /dev/null +++ b/core/docs/decisions/0014-tls-mode-of-a-new-connection.md @@ -0,0 +1,66 @@ +# 0014: A new connection starts on the TLS mode the engine's own client starts on + +- **Status**: Accepted +- **Date**: 2026-11-05 + +## Context + +The apps started a new connection on three different modes: Linux on Verify full wherever the driver offered it, Windows on Disable, and macOS on each driver's own default. On Linux a new connection to a local PostgreSQL or MySQL without TLS failed on the first connect, and the error offered no fix. The core had no mode for TLS when the server offers it, so neither app on the core could start where psql and mysql start. + +What each engine's own client starts on, read from its documentation and source in November 2026: + +| Engine | Client | Starts on | +|---|---|---| +| PostgreSQL | libpq, `sslmode=prefer` ([libpq-connect](https://www.postgresql.org/docs/current/libpq-connect.html), `fe-connect.c` on REL_18_STABLE) | TLS when the server offers it, plain otherwise; the certificate is not checked | +| MySQL | `mysql` 8.4 and 9.x, `--ssl-mode=PREFERRED` ([connection options](https://dev.mysql.com/doc/refman/8.4/en/connection-options.html)) | The same; a handshake that fails is an error | +| MariaDB | the 11.4 client and Connector/C 3.4 (MDEV-31855, MDEV-31856, MDEV-31857) | TLS required and checked, where a self-signed certificate passes on a fingerprint derived from the password | +| SQL Server | ODBC Driver 18, Microsoft.Data.SqlClient 4 and later, SSMS 20 and later, sqlcmd on ODBC 18 ([encryption and certificate validation](https://learn.microsoft.com/en-us/sql/connect/ado-net/encryption-and-certificate-validation)) | `Encrypt=Mandatory` with `TrustServerCertificate=false`: TLS with the chain and the name checked. go-sqlcmd alone encrypts only the login and trusts any certificate | +| MongoDB | mongosh ([connection string options](https://www.mongodb.com/docs/manual/reference/connection-string-options/)) | Plain for `mongodb://`; TLS with the certificate checked for `mongodb+srv://` | +| Redis, Valkey | redis-cli, valkey-cli ([redis-cli](https://redis.io/docs/latest/develop/tools/cli/)) | Plain unless `--tls` or `rediss://` | +| Cassandra, ScyllaDB | cqlsh (`DEFAULT_SSL = False` in `cqlshmain.py`) | Plain | +| ClickHouse | clickhouse-client (`ConnectionParameters.cpp`) | Plain, and secure on its secure port 9440 or a ClickHouse Cloud host | + +## Decision + +A new connection starts on the mode the engine's own client starts on for what the user typed. The core holds it: `TlsCapabilities::default_mode` and `tls_ports` per driver, and `DriverCapabilities::new_connection_tls(port, options)` for the rule, which every app reads. The core gains `TlsMode::Prefer` for the engines that negotiate TLS inside their protocol. Every TLS failure that a change of mode fixes offers Change Encryption. + +| Engine | A new connection starts on | +|---|---| +| PostgreSQL | Prefer | +| MySQL, MariaDB | Prefer | +| SQL Server | Verify full | +| MongoDB | Disable, or Verify full with a DNS seed list | +| Redis | Disable | +| Cassandra, ScyllaDB | Disable | +| ClickHouse | Disable, or Verify full on its HTTPS ports 8443 and 443 | +| SQLite, DuckDB | No TLS | + +## Rationale + +- A user who types the host, port and login they give psql, mysql, sqlcmd or mongosh expects to connect where that client connects. A default stricter than the engine's client fails on the most common server, a local one, with a setting the user never chose. A default looser than it gives away a check the user already had. +- The standard is each engine's own client, not one mode for every engine, because the engines differ. PostgreSQL and MySQL ask for TLS inside their protocol and can go on without it. The others decide TLS by the port before the first byte, so their clients start plain and turn TLS on only when told. +- Prefer is what libpq and mysql call it and what they do: ask for TLS, go on in the clear when the server has none, and not check the certificate. tokio-postgres 0.7.18 (`SslMode::Prefer`, `connect_tls.rs`) and sqlx-mysql 0.9.0 (`MySqlSslMode::Preferred`, `connection/tls.rs`) do the same. A Prefer that checked the certificate would fail on every self-signed server where psql connects. +- MariaDB departs from its own client. One driver serves both servers and tells them apart only after it connects, and sqlx has no fingerprint check, so Verify full would fail on every stock 11.4 server, which makes its own self-signed certificate. Prefer encrypts against each of them. +- SQL Server starts on Verify full because ODBC Driver 18, Microsoft.Data.SqlClient 4 and SSMS 20 all check the certificate by default. go-sqlcmd's looser default is the exception among Microsoft's clients. +- ClickHouse's HTTP interface has no secure native port, so its HTTPS ports stand where clickhouse-client's 9440 does. A ClickHouse Cloud service takes HTTP only over TLS on 8443, which the port rule already covers. + +### What Prefer protects + +- Prefer stops a passive listener when the server offers TLS. It does not stop an active attacker, who can answer that the server has no TLS or present any certificate. PostgreSQL rates prefer as "Maybe" against eavesdropping and "No" against a man in the middle, and keeps it as libpq's default only for backward compatibility ([libpq-ssl](https://www.postgresql.org/docs/current/libpq-ssl.html)). MySQL calls VERIFY_CA and VERIFY_IDENTITY a better choice than the default. +- So the apps say what it does where it is chosen. On Linux the Encryption row's subtitle under Prefer reads "Encrypted if the server offers TLS, otherwise not. The server certificate is not checked.", in the short, plain and neutral form the GNOME HIG's Writing style asks for. On Windows the mode reads "Preferred, any certificate". Verify full is one choice away, and an import names a connection looser than a new one. + +## Consequences + +- The UI keeps the mode on the engine's default until the user picks one, as the port follows the driver: a driver switch, a DNS seed list and a port that serves only TLS move it. A saved connection keeps the mode it was saved with, so a later edit never weakens it. +- `ServerRefusedTls` offers Change Encryption. Under Disable, Redis, MongoDB, Cassandra and ClickHouse check a plain login the server dropped with a TLS handshake of their own, sent with no credential, and report a server that completes it as `ServerRequiresTls`, as SQL Server already did. The other way round, a Redis without TLS reads the hello as a command and waits for its newline, so a handshake that times out is checked with a plain `PING` and reported as `ServerRefusedTls` when the server answers it. +- Foreign import keeps another app's Preferred as Prefer where the engine offers it, and the nearest stronger mode where it does not. A connection URL's `sslmode=prefer`, `sslmode=allow` and `ssl-mode=PREFERRED` read as Prefer, `mongodb+srv://` as Verify full, and a URL that trusts any certificate (`TrustServerCertificate`, `tlsAllowInvalidCertificates`, `tlsInsecure`) as Require. +- libpq retries in the clear after a TLS handshake that fails; tokio-postgres does not, and neither do sqlx and the mysql client. A PostgreSQL server that agrees to TLS and then fails the handshake fails the connect. +- The macOS app keeps its own defaults until its connection form moves onto the core ([ADR 0010](0010-macos-on-the-core.md)). They match this rule except for SQL Server, which it starts on Preferred (FreeTDS `encryption=request`). +- The connection list stores `prefer` without a new file version, as it does `strict`: no released build reads the file yet ([Linux ADR 0033](../../../linux/docs/decisions/0033-no-compatibility-with-pre-release-states.md)). + +## Alternatives considered + +- **Verify full for every engine.** It is the strongest mode, and what Linux started on in development, but it fails on a local server and on every self-signed one, where the engine's own client connects. +- **Disable for every engine,** as Windows had. It reaches a local server, and sends the login in the clear to a server that offers TLS. +- **Require for PostgreSQL and MySQL.** It fails on a server without TLS, where psql and mysql connect. +- **A default in each app.** Three apps drifted into three defaults. The core is the one place every app reads. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index a78abbad3b..202c9f2576 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -21,5 +21,6 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0011](0011-sql-dump-and-import-in-process.md) | SQL dumps and SQL file imports run in process | Accepted | Export Database writes one `.sql` file from each driver's catalog read in `pg_dump` and `mysqldump` order, and Import SQL File splits a file of any size as the engine's client does and runs it on an editor session; no app calls `pg_dump` or `mysqldump`. | | [0012](0012-copies-before-a-format-upgrade.md) | A file in an older format is copied beside itself before its first write in the newer one | Accepted | `write_document_blocking` and the history's open copy a file an older build wrote to `.v-` before replacing it, the history through `VACUUM INTO`; three kept per file; no copy, no write. | | [0013](0013-catalog-operations.md) | Truncating a table and creating or dropping a schema or database | Accepted | `DdlDialect` plans TRUNCATE and CREATE and DROP for schemas and databases per engine, MongoDB through its shell; a database change runs outside any transaction as `WriteKind::DatabaseChanges`; a login to a missing database fails as `DatabaseNotFound` and parks. | +| [0014](0014-tls-mode-of-a-new-connection.md) | A new connection starts on the TLS mode the engine's own client starts on | Accepted | `TlsMode::Prefer` for PostgreSQL and MySQL, Verify full for SQL Server, Disable for the engines that decide TLS by the port, with a DNS seed list and ClickHouse's HTTPS ports on Verify full; the core holds the rule, and every TLS failure a mode change fixes offers Change Encryption. | | [0015](0015-editing-a-query-result.md) | A query result edits when its statement reads one table and its driver traces the columns | Accepted | The parser accepts one row-preserving SELECT over one table; each driver sets `ResultColumn::origin` only for a direct column of a permanent base table, from the wire or a lookup on its own connection; the result maps to the catalog with its full primary key and saves through `plan_save`. | | [0016](0016-tablepro-accounts.md) | TablePro accounts live in the core, with features gated by the entitlement | Accepted | `tablepro-account` signs in through the browser with OAuth and a loopback redirect, registers the device, verifies the Ed25519 entitlement and gates features by its codes; each app passes its keyring, browser, machine ID and OAuth client in. | diff --git a/linux/ROADMAP.md b/linux/ROADMAP.md index 5ee8e93ded..b8de2d4a91 100644 --- a/linux/ROADMAP.md +++ b/linux/ROADMAP.md @@ -39,9 +39,9 @@ The app runs on GNOME 50 ([ADR 0015](docs/decisions/0015-gnome-50-platform-floor | Capability | Detail | |---|---| -| Modes | Disable, Require and Verify full; Verify full is the default for a new connection | +| Modes | Disable, Prefer (PostgreSQL and MySQL), Require and Verify full; a new connection starts on the mode the engine's own client starts on ([core ADR 0014](../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)) | | Certificates | CA file, client certificate and key (every network engine but SQL Server), and a server name override (MySQL only through an SSH tunnel) | -| Remedies | A TLS failure says what went wrong. An unknown issuer jumps to the CA file, and a name mismatch to the server name | +| Remedies | A TLS failure says what went wrong. An unknown issuer jumps to the CA file, a name mismatch to the server name, and a server that refuses or requires TLS to the Encryption row | ### Browse and edit @@ -229,7 +229,7 @@ What has to hold before the first release, for a user on GNOME 50 with Ubuntu 26 | 3 | Browses tables of real-world data (dates, decimals, JSON, UUIDs, NULLs) and sees correct values | Per-engine decoding with the type fallback and unsupported-type conformance cases ([ADR 0014](docs/decisions/0014-lossless-values-and-dialects.md)). A value corpus on every engine, MariaDB too: dates and times at their extremes and in other zones, decimals, JSON, UUIDs, Unicode and binary values, read back through a table tab, Export All and an editor run, and exported as CSV and SQL INSERT and loaded back into an empty copy | Nothing | | 4 | Runs typical queries against tables of a million rows or more without running out of memory or freezing | The 10,000-row editor limit with Export All, and driver tests over 2,000,000 rows. Pages seek past the edge row's key, or walk PostgreSQL heap block windows for a table with no key; OFFSET only under a user sort, a restored deep offset or a partitioned keyless table. Docker tests page 60k and 25k-row tables both ways and check the plan. A 1,000,000-row table is paged to its end and exported on PostgreSQL, MySQL, MariaDB, SQL Server, ClickHouse, Cassandra, ScyllaDB, SQLite and DuckDB, with bounds on time and on resident peak growth. The file engines' cases run in the unit suite, each in a test binary of its own, so the peak is its alone | Nothing | | 5 | Edits data in place, and the changes commit correctly even when the connection or the app misbehaves | Write, row guard and commit resolution conformance on every engine, with the fault fakes and the grid save Docker test. `kill_during_save` kills TablePro halfway through a SQLite save: the file keeps none of it, and the next launch restores the session with its history, settings and saved tabs. A save into a SQLite file another program holds locked fails as `Busy(FileLocked)`, which says another program or an editor tab holds the file's lock, and leaves the file as it was whether the lock shows at `BEGIN IMMEDIATE` or at the `COMMIT` | Nothing | -| 6 | Trusts the app with credentials: TLS, SSH tunnels, no password in plain text | Verify full by default, the TLS conformance suite, the Secret Service, and statement logging silenced | An outside security review | +| 6 | Trusts the app with credentials: TLS, SSH tunnels, no password in plain text | Each engine's own client TLS default, Verify full one choice away, the TLS conformance suite, the Secret Service, and statement logging silenced | An outside security review | | 7 | Recovers when the network drops or the database restarts | Health monitoring, backoff and replay rules with their tests, a stopped container in the liveness tests, and a session test that restarts PostgreSQL: the read in flight runs again, the save in flight does not and leaves no row | Nothing | | 8 | Works with a screen reader, the keyboard alone and larger text | Label audits of the picker, the connect pages, the workspace, the connect dialog and preferences, labelled cells and real-key tests. Sorting from the cell menu, named filter fields and cell editors, focus handed on when a control hides, and announced query results and errors. Columns move and resize from the keyboard, and a column sized by a key or a header drag draws at that width, also when it comes back. The ER diagram's tables are focusable list items that name their columns and joins | The manual pass in the backlog | | 9 | Sees no message that cannot be translated, even while only English ships | Every string the app writes is in the template. Core errors carry values the app words itself: CSV import, cell and JSON parsing, type and default syntax, the keyring, certificate files, unsupported features, the SSH host, username and jump host checks, a failed write of the saved connections, the SSH runtime directory checks, ssh's exit status, and an ssh that would not start. A panic, an export encoder failure, an SSH failure with no sentence of its own and a TLS failure the app does not classify show the app's words and log the detail | Nothing | diff --git a/linux/changelog.d/4051.changed.md b/linux/changelog.d/4051.changed.md new file mode 100644 index 0000000000..9b76a218ff --- /dev/null +++ b/linux/changelog.d/4051.changed.md @@ -0,0 +1 @@ +A new connection starts on the TLS mode the database's own client uses, such as Prefer for PostgreSQL and MySQL. diff --git a/linux/changelog.d/4051.fixed.1.md b/linux/changelog.d/4051.fixed.1.md new file mode 100644 index 0000000000..49c6082a1d --- /dev/null +++ b/linux/changelog.d/4051.fixed.1.md @@ -0,0 +1 @@ +A connect the server refused over its TLS setting offered no way to change the encryption. diff --git a/linux/changelog.d/4051.fixed.md b/linux/changelog.d/4051.fixed.md new file mode 100644 index 0000000000..d4ee793e76 --- /dev/null +++ b/linux/changelog.d/4051.fixed.md @@ -0,0 +1 @@ +A new PostgreSQL or MySQL connection to a server without TLS failed on the first connect. diff --git a/linux/crates/app/src/ui/connect_dialog/connect_form.rs b/linux/crates/app/src/ui/connect_dialog/connect_form.rs index 0faa74a67d..831832cf4c 100644 --- a/linux/crates/app/src/ui/connect_dialog/connect_form.rs +++ b/linux/crates/app/src/ui/connect_dialog/connect_form.rs @@ -24,6 +24,10 @@ use crate::ui::ssh_inputs::{SshFormState, SshInputError, SshSecretToStore}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TlsFormState { pub mode: TlsMode, + /// Set once the user picks a mode, and for a saved connection, whose + /// mode was picked when it was saved. Until then the mode follows the + /// driver's default. + pub mode_chosen: bool, pub ca_file: Option, pub client_certificate: Option, pub client_key: Option, @@ -31,9 +35,10 @@ pub struct TlsFormState { } impl TlsFormState { - pub fn new(caps: Option<&TlsCapabilities>) -> Self { + pub fn new(mode: TlsMode) -> Self { Self { - mode: default_tls_mode(caps), + mode, + mode_chosen: false, ca_file: None, client_certificate: None, client_key: None, @@ -44,6 +49,7 @@ impl TlsFormState { pub fn from_config(config: &TlsConfig) -> Self { Self { mode: config.mode, + mode_chosen: true, ca_file: config.ca_file.clone(), client_certificate: config .client_identity @@ -80,17 +86,6 @@ impl TlsFormState { } } -/// Verify full proves who is on the other end and, unlike Strict, works -/// with any server version, so a new connection starts there whenever -/// the driver offers it. -pub fn default_tls_mode(caps: Option<&TlsCapabilities>) -> TlsMode { - match caps { - Some(caps) if caps.modes.contains(&TlsMode::VerifyFull) => TlsMode::VerifyFull, - Some(caps) => caps.modes.last().copied().unwrap_or(TlsMode::Disable), - None => TlsMode::Disable, - } -} - /// Whether the driver can check the certificate against another name /// on this route. MySQL only can over an SSH forward, where the name it /// dials is the forward's and never the certificate's. @@ -154,18 +149,19 @@ pub struct ValidatedForm { impl ConnectForm { pub fn new(driver_id: &str, caps: &DriverCapabilities) -> Self { + let port = caps.default_port().unwrap_or(1); Self { name: String::new(), driver_id: driver_id.to_owned(), host: String::new(), - port: caps.default_port().unwrap_or(1), + port, port_edited: false, database: String::new(), auth: caps.auth_modes.first().copied().unwrap_or_default(), username: String::new(), password: SecretString::from(String::new()), remember_password: true, - tls: TlsFormState::new(caps.tls.as_ref()), + tls: TlsFormState::new(caps.new_connection_tls(port, &NetworkOptions::default())), safe_mode: SafeModeLevel::Off, external_access: ExternalAccess::default(), ai_policy: AiPolicy::default(), @@ -223,10 +219,18 @@ impl ConnectForm { if !caps.auth_modes.is_empty() && !caps.supports(self.auth) { self.auth = caps.auth_modes.first().copied().unwrap_or_default(); } - if let Some(tls) = caps.tls.as_ref() - && !tls.modes.contains(&self.tls.mode) - { - self.tls.mode = default_tls_mode(Some(tls)); + self.follow_tls_default(caps); + } + + /// Start the mode where a new connection with these options starts, + /// unless the user picked one this driver offers. + pub fn follow_tls_default(&mut self, caps: &DriverCapabilities) { + let Some(tls) = caps.tls.as_ref() else { + return; + }; + if !self.tls.mode_chosen || !tls.modes.contains(&self.tls.mode) { + self.tls.mode = caps.new_connection_tls(self.port, &self.options); + self.tls.mode_chosen = false; } } @@ -437,6 +441,7 @@ impl ConnectForm { } if let Some(mode) = url.tls.mode.filter(|mode| tls_caps.modes.contains(mode)) { form.tls.mode = mode; + form.tls.mode_chosen = true; } form.tls.ca_file = url.tls.ca_file; form.tls.client_certificate = url.tls.client_certificate; @@ -812,6 +817,10 @@ mod tests { caps(&tablepro_driver_mongodb::MongoDriver) } + fn clickhouse() -> &'static DriverCapabilities { + caps(&tablepro_driver_clickhouse::ClickhouseDriver) + } + fn filled(driver_id: &str, caps: &DriverCapabilities) -> ConnectForm { ConnectForm { host: "db.example.com".to_owned(), @@ -836,13 +845,96 @@ mod tests { } #[test] - fn verify_full_is_default() { - for caps in [postgres(), mysql(), mssql()] { - assert_eq!(ConnectForm::new("x", caps).tls.mode, TlsMode::VerifyFull); + fn a_new_connection_starts_on_the_mode_the_engines_own_client_starts_on() { + let cases = [ + (postgres(), TlsMode::Prefer), + (mysql(), TlsMode::Prefer), + (mssql(), TlsMode::VerifyFull), + (redis(), TlsMode::Disable), + (mongodb(), TlsMode::Disable), + ]; + for (caps, mode) in cases { + assert_eq!(ConnectForm::new("x", caps).tls.mode, mode); } let form = filled("postgres", postgres()); let valid = form.validate(postgres()).expect("a valid form"); - assert_eq!(network(&valid.target).3, &TlsConfig::verify_full()); + assert_eq!( + network(&valid.target).3, + &TlsConfig { + mode: TlsMode::Prefer, + ..TlsConfig::disabled() + } + ); + } + + #[test] + fn the_mode_follows_the_driver_until_the_user_picks_one() { + let mut form = ConnectForm::new("redis", redis()); + form.switch_driver("postgres", postgres()); + assert_eq!(form.tls.mode, TlsMode::Prefer, "the default stayed on Redis's"); + + form.switch_driver("mssql", mssql()); + assert_eq!(form.tls.mode, TlsMode::VerifyFull); + + form.tls.mode = TlsMode::Disable; + form.tls.mode_chosen = true; + form.switch_driver("mysql", mysql()); + assert_eq!(form.tls.mode, TlsMode::Disable, "a picked mode was replaced"); + + form.tls.mode = TlsMode::Prefer; + form.switch_driver("mssql", mssql()); + assert_eq!(form.tls.mode, TlsMode::VerifyFull, "a mode SQL Server lacks was kept"); + assert!(!form.tls.mode_chosen); + } + + #[test] + fn a_seed_list_starts_tls_on_until_the_user_picks_a_mode() { + let mut form = ConnectForm::new("mongodb", mongodb()); + form.options.dns_seed_list = true; + form.follow_tls_default(mongodb()); + assert_eq!(form.tls.mode, TlsMode::VerifyFull); + + form.options.dns_seed_list = false; + form.follow_tls_default(mongodb()); + assert_eq!(form.tls.mode, TlsMode::Disable); + + form.tls.mode = TlsMode::Require; + form.tls.mode_chosen = true; + form.options.dns_seed_list = true; + form.follow_tls_default(mongodb()); + assert_eq!(form.tls.mode, TlsMode::Require); + } + + #[test] + fn a_port_that_serves_only_tls_starts_tls_on() { + let mut form = ConnectForm::new("clickhouse", clickhouse()); + assert_eq!(form.tls.mode, TlsMode::Disable); + + form.port = 8443; + form.follow_tls_default(clickhouse()); + assert_eq!(form.tls.mode, TlsMode::VerifyFull); + + form.port = 8123; + form.follow_tls_default(clickhouse()); + assert_eq!(form.tls.mode, TlsMode::Disable); + } + + #[test] + fn a_saved_mode_stays_when_the_port_moves() { + let mut typed = ConnectForm { + port: 8443, + port_edited: true, + ..filled("clickhouse", clickhouse()) + }; + typed.follow_tls_default(clickhouse()); + let saved = saved_from(&typed, clickhouse()); + assert_eq!(saved.tls.mode, TlsMode::VerifyFull); + + let mut reopened = ConnectForm::from_saved(&saved, clickhouse()); + reopened.port = 8444; + reopened.follow_tls_default(clickhouse()); + + assert_eq!(reopened.tls.mode, TlsMode::VerifyFull, "a saved mode was weakened"); } #[test] @@ -1157,6 +1249,8 @@ mod tests { let mut form = filled("postgres", postgres()); form.port = 6543; form.port_edited = true; + form.tls.mode = TlsMode::VerifyFull; + form.tls.mode_chosen = true; form.tls.ca_file = Some(PathBuf::from("/etc/tls/ca.pem")); form.ssh = Some(SshFormState { host: "bastion".to_owned(), diff --git a/linux/crates/app/src/ui/connect_dialog/mod.rs b/linux/crates/app/src/ui/connect_dialog/mod.rs index 4ab4d91cb1..a4b2100282 100644 --- a/linux/crates/app/src/ui/connect_dialog/mod.rs +++ b/linux/crates/app/src/ui/connect_dialog/mod.rs @@ -298,6 +298,20 @@ impl ConnectDialog { && !dialog.imp().updating.get() { dialog.show_seed_list_rows(); + dialog.follow_tls_default(); + dialog.refresh(); + } + }); + } + + fn connect_port_row(&self) { + let weak = self.downgrade(); + self.imp().port_row.connect_value_notify(move |_| { + if let Some(dialog) = weak.upgrade() + && !dialog.imp().updating.get() + { + dialog.imp().port_edited.set(true); + dialog.follow_tls_default(); dialog.refresh(); } }); @@ -519,15 +533,7 @@ impl ConnectDialog { dialog.switch_driver(); } }); - let weak = self.downgrade(); - imp.port_row.connect_value_notify(move |_| { - if let Some(dialog) = weak.upgrade() - && !dialog.imp().updating.get() - { - dialog.imp().port_edited.set(true); - dialog.refresh(); - } - }); + self.connect_port_row(); let weak = self.downgrade(); imp.safe_mode_row.connect_selected_notify(move |_| { if let Some(dialog) = weak.upgrade() { @@ -917,6 +923,22 @@ impl ConnectDialog { self.show_seed_list_rows(); } + /// A seed list or a port that serves only TLS starts TLS on, so the + /// mode moves with them until the user picks one. + fn follow_tls_default(&self) { + let Some(entry) = self.current_entry() else { + return; + }; + let caps = entry.capabilities(); + let mut form = self.form(); + let before = form.tls.mode; + form.follow_tls_default(caps); + if form.tls.mode != before { + self.imp().tls_section.apply(caps.tls.as_ref(), self.route(), &form.tls); + self.recheck_files(); + } + } + /// The TLS settings the request would carry, for the file check. fn tls_config(&self) -> TlsConfig { let Some(entry) = self.current_entry() else { diff --git a/linux/crates/app/src/ui/connect_dialog/tests.rs b/linux/crates/app/src/ui/connect_dialog/tests.rs index eed7ed73f0..7956844f70 100644 --- a/linux/crates/app/src/ui/connect_dialog/tests.rs +++ b/linux/crates/app/src/ui/connect_dialog/tests.rs @@ -143,6 +143,19 @@ fn fill_network(dialog: &ConnectDialog) { imp.password_row.set_text("s3cret"); } +/// Pick an encryption mode in the dialog, as the user does. +fn select_mode(dialog: &ConnectDialog, mode: TlsMode) { + let section = dialog.imp().tls_section.get(); + let index = section + .imp() + .modes + .borrow() + .iter() + .position(|offered| *offered == mode) + .unwrap_or_else(|| panic!("{mode:?} is not offered")); + section.imp().encryption_row.set_selected(index as u32); +} + fn caps_of(driver_id: &str) -> &'static DriverCapabilities { registry() .get(driver_id) @@ -337,10 +350,35 @@ fn encryption_combo_lists_only_capability_modes() { tls.modes.len(), "{driver_id}" ); - assert_eq!(harness.dialog.form().tls.mode, TlsMode::VerifyFull, "{driver_id}"); + assert_eq!(harness.dialog.form().tls.mode, tls.default_mode, "{driver_id}"); } } +#[gtk4::test] +fn the_encryption_row_follows_the_default_until_a_mode_is_picked() { + let harness = dialog(); + let imp = harness.dialog.imp(); + let mode = || harness.dialog.form().tls.mode; + + select(&harness.dialog, "mongodb"); + assert_eq!(mode(), TlsMode::Disable); + imp.seed_list_row.set_active(true); + assert_eq!(mode(), TlsMode::VerifyFull, "a seed list starts TLS on"); + imp.seed_list_row.set_active(false); + assert_eq!(mode(), TlsMode::Disable); + + select(&harness.dialog, "clickhouse"); + imp.port_row.set_value(8443.0); + assert_eq!(mode(), TlsMode::VerifyFull, "the HTTPS port starts TLS on"); + + select_mode(&harness.dialog, TlsMode::Require); + imp.port_row.set_value(8123.0); + assert_eq!(mode(), TlsMode::Require, "a picked mode followed the port"); + + select(&harness.dialog, "postgres"); + assert_eq!(mode(), TlsMode::Require, "a picked mode followed the driver"); +} + /// Each encryption mode and SSH method beside the subtitle that /// describes it, in the dialog at its own width. #[gtk4::test] @@ -664,6 +702,7 @@ fn a_test_connect_runs_under_the_connection_query_timeout() { fn connect_insensitive_while_pem_check_pending() { let harness = dialog(); fill_network(&harness.dialog); + select_mode(&harness.dialog, TlsMode::VerifyFull); let root = tempfile::tempdir().expect("tempdir"); let ca = root.path().join("ca.pem"); std::fs::write(&ca, b"-----BEGIN CERTIFICATE-----\nnot base64\n").expect("write"); @@ -689,6 +728,7 @@ fn invalid_ca_marks_row_error_and_disables_connect() { let ca = root.path().join("ca.pem"); std::fs::write(&ca, b"this is not a certificate").expect("write"); let imp = harness.dialog.imp(); + select_mode(&harness.dialog, TlsMode::VerifyFull); imp.tls_section.set_file_path(FormField::CaFile, Some(ca)); wait_until(WAIT, || matches!(imp.pem.state(), PemState::Invalid(_))).expect("the file check"); @@ -747,7 +787,7 @@ fn connect_emits_submission_without_establishing() { let RequestTarget::Network { tls, .. } = &submission.request.target else { panic!("expected a network target"); }; - assert_eq!(tls.mode, TlsMode::VerifyFull); + assert_eq!(tls.mode, TlsMode::Prefer); } #[gtk4::test] diff --git a/linux/crates/app/src/ui/connect_dialog/tls_section.rs b/linux/crates/app/src/ui/connect_dialog/tls_section.rs index 93189b1379..6fe5410168 100644 --- a/linux/crates/app/src/ui/connect_dialog/tls_section.rs +++ b/linux/crates/app/src/ui/connect_dialog/tls_section.rs @@ -7,7 +7,7 @@ use libadwaita as adw; use libadwaita::prelude::*; use tablepro_core::{ConfigError, TlsCapabilities, TlsConfig, TlsMode, TransportClass}; -use super::connect_form::{TlsFormState, default_tls_mode, shows_server_name, tls_field}; +use super::connect_form::{TlsFormState, shows_server_name, tls_field}; use super::form_errors::FormErrors; use super::form_field::FormField; use super::row_problem::show_problem; @@ -64,6 +64,8 @@ mod imp { pub ca_file: RefCell>, pub client_certificate: RefCell>, pub client_key: RefCell>, + /// Set once the user picks a mode; see `TlsFormState::mode_chosen`. + pub mode_chosen: Cell, /// Set while the code writes the rows, so its own writes are not /// reported as the user changing them. pub updating: Cell, @@ -107,6 +109,7 @@ mod imp { if let Some(section) = weak.upgrade() && !section.imp().updating.get() { + section.imp().mode_chosen.set(true); section.refresh_rows(); section.emit_changed(); } @@ -183,8 +186,9 @@ impl TlsSection { let mode = if caps.modes.contains(&state.mode) { state.mode } else { - default_tls_mode(Some(caps)) + caps.default_mode }; + imp.mode_chosen.set(state.mode_chosen && mode == state.mode); let index = caps.modes.iter().position(|candidate| *candidate == mode).unwrap_or(0); imp.encryption_row.set_selected(index as u32); imp.ca_file.replace(state.ca_file.clone()); @@ -205,6 +209,7 @@ impl TlsSection { let imp = self.imp(); TlsFormState { mode: self.mode(), + mode_chosen: imp.mode_chosen.get(), ca_file: imp.ca_file.borrow().clone(), client_certificate: imp.client_certificate.borrow().clone(), client_key: imp.client_key.borrow().clone(), @@ -380,6 +385,7 @@ impl TlsSection { pub fn mode_label(mode: TlsMode) -> String { match mode { TlsMode::Disable => crate::i18n::gettext("Disable"), + TlsMode::Prefer => crate::i18n::gettext("Prefer"), TlsMode::Require => crate::i18n::gettext("Require"), TlsMode::VerifyFull => crate::i18n::gettext("Verify full"), TlsMode::Strict => crate::i18n::gettext("Strict"), @@ -392,6 +398,9 @@ pub fn mode_description(mode: TlsMode) -> String { TlsMode::Disable => crate::i18n::gettext( "Not encrypted. Anyone on the network can read or change the traffic, password included.", ), + TlsMode::Prefer => crate::i18n::gettext( + "Encrypted if the server offers TLS, otherwise not. The server certificate is not checked.", + ), TlsMode::Require => crate::i18n::gettext("Encrypted. The server certificate is not checked."), TlsMode::VerifyFull => crate::i18n::gettext("Encrypted. The certificate must be valid for the server name."), TlsMode::Strict => crate::i18n::gettext( diff --git a/linux/crates/app/src/ui/error_text/tls_remedy.rs b/linux/crates/app/src/ui/error_text/tls_remedy.rs index da18e5db14..3f52963f63 100644 --- a/linux/crates/app/src/ui/error_text/tls_remedy.rs +++ b/linux/crates/app/src/ui/error_text/tls_remedy.rs @@ -28,13 +28,13 @@ pub fn remedy(failure: TlsFailure) -> Option { match failure { TlsFailure::UnknownIssuer => Some(TlsRemedy::ChooseCaCertificate), TlsFailure::NameMismatch => Some(TlsRemedy::SetServerName), - TlsFailure::ServerRequiresTls | TlsFailure::ServerRefusedStrict | TlsFailure::ServerRequiresStrict => { - Some(TlsRemedy::ChangeEncryption) - } + TlsFailure::ServerRefusedTls + | TlsFailure::ServerRequiresTls + | TlsFailure::ServerRefusedStrict + | TlsFailure::ServerRequiresStrict => Some(TlsRemedy::ChangeEncryption), TlsFailure::Expired | TlsFailure::NotYetValid | TlsFailure::Revoked - | TlsFailure::ServerRefusedTls | TlsFailure::HandshakeRejected | TlsFailure::CaFileInvalid | TlsFailure::ClientIdentityInvalid @@ -63,6 +63,7 @@ mod tests { assert_eq!(remedy(TlsFailure::UnknownIssuer), Some(TlsRemedy::ChooseCaCertificate)); assert_eq!(remedy(TlsFailure::NameMismatch), Some(TlsRemedy::SetServerName)); for failure in [ + TlsFailure::ServerRefusedTls, TlsFailure::ServerRequiresTls, TlsFailure::ServerRefusedStrict, TlsFailure::ServerRequiresStrict, @@ -112,6 +113,16 @@ mod tests { ); } + #[test] + fn a_server_without_tls_offers_the_encryption_row() { + let error = ConnectError::Driver(DriverError::Tls { + failure: TlsFailure::ServerRefusedTls, + detail: "server does not support TLS".to_owned(), + }); + + assert_eq!(connect_remedy(&error, true), Some(TlsRemedy::ChangeEncryption)); + } + #[test] fn a_closed_strict_connect_offers_the_encryption_row() { let error = ConnectError::Driver(DriverError::Tls { diff --git a/linux/crates/app/src/ui/import_preview.rs b/linux/crates/app/src/ui/import_preview.rs index cffc9c810d..5b496297c0 100644 --- a/linux/crates/app/src/ui/import_preview.rs +++ b/linux/crates/app/src/ui/import_preview.rs @@ -6,7 +6,6 @@ use tablepro_core::{AiPolicy, DriverCapabilities, DriverRegistry, ExternalAccess use tablepro_storage::{ImportChange, ImportEntry, ImportPreview, SavedSshConfig}; use crate::services::saved_connection_object::subtitle_for; -use crate::ui::connect_dialog::ConnectForm; pub(crate) const IMPORT: &str = "import"; const CANCEL: &str = "cancel"; @@ -80,7 +79,7 @@ fn entry_text(entry: &ImportEntry, drivers: &DriverRegistry) -> EntryText { lines.extend(saved.ssh.as_ref().map(ssh_hop)); } if let Some(caps) = caps { - let new_connection = ConnectForm::new(&saved.driver_id, caps).tls.mode; + let new_connection = caps.new_connection_tls(saved.port, &saved.options); lines.extend(looser_tls(saved.tls.mode, new_connection)); } lines.extend(looser_settings(saved.external_access, saved.ai_policy)); @@ -197,6 +196,11 @@ fn looser_tls(mode: TlsMode, new_connection: TlsMode) -> Option { if new_connection.encrypts() && !mode.encrypts() { return Some(crate::i18n::gettext("Connects without TLS")); } + if new_connection.requires_tls() && !mode.requires_tls() { + return Some(crate::i18n::gettext( + "Connects without TLS when the server does not offer it", + )); + } if new_connection.verifies_certificate() && !mode.verifies_certificate() { return Some(crate::i18n::gettext( "Connects over TLS without checking the certificate", @@ -258,6 +262,24 @@ mod tests { assert_eq!(looser_tls(TlsMode::Disable, TlsMode::Disable), None); } + #[test] + fn prefer_is_looser_than_a_mode_that_requires_tls_and_not_than_itself() { + assert_eq!( + looser_tls(TlsMode::Disable, TlsMode::Prefer).as_deref(), + Some("Connects without TLS") + ); + assert_eq!(looser_tls(TlsMode::Prefer, TlsMode::Prefer), None); + assert_eq!(looser_tls(TlsMode::Require, TlsMode::Prefer), None); + assert_eq!( + looser_tls(TlsMode::Prefer, TlsMode::Require).as_deref(), + Some("Connects without TLS when the server does not offer it") + ); + assert_eq!( + looser_tls(TlsMode::Prefer, TlsMode::VerifyFull).as_deref(), + Some("Connects without TLS when the server does not offer it") + ); + } + #[test] fn strict_checks_the_certificate_and_also_encrypts_the_prelogin_exchange() { for default in [TlsMode::Disable, TlsMode::Require, TlsMode::VerifyFull, TlsMode::Strict] { diff --git a/linux/docs/drivers/cassandra.md b/linux/docs/drivers/cassandra.md index 4896e0266e..cfca317b08 100644 --- a/linux/docs/drivers/cassandra.md +++ b/linux/docs/drivers/cassandra.md @@ -24,8 +24,10 @@ The session names itself to the server as TablePro with the app's version. The u ## TLS +- A new connection starts on `Disable`, as cqlsh does ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). - `VerifyFull` trusts the system store plus the connection's CA file ([Trust](../../../core/ARCHITECTURE.md#trust)) and checks the certificate against `NetworkTarget::tls_server_name()`. scylla hands rustls the relay's address, so the driver's verifier checks the configured name instead (`tablepro_net::tls::FixedNameVerifier`). `Require` encrypts without checking the certificate. - A client certificate is sent when one is set. Both servers ask every client for one or none (`require_client_auth`), and still log the role in by its password. +- With TLS off, a connect the node drops is checked with a TLS handshake of its own, which sends no credential, and is reported as `TlsFailure::ServerRequiresTls` when the node completes it. ## Read-only diff --git a/linux/docs/drivers/clickhouse.md b/linux/docs/drivers/clickhouse.md index c92ce373fd..03d8631b09 100644 --- a/linux/docs/drivers/clickhouse.md +++ b/linux/docs/drivers/clickhouse.md @@ -39,9 +39,11 @@ Results stream as `JSONCompactEachRowWithNamesAndTypes`, and each cell is read b ## TLS +- A new connection starts on `Disable`, as clickhouse-client does, and on `VerifyFull` while the port is 8443 or 443, which serve only HTTPS ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). - `VerifyFull` trusts the system store plus the connection's CA file ([Trust](../../../core/ARCHITECTURE.md#trust)) and checks the name from `NetworkTarget::tls_server_name()`. `Require` encrypts without checking the certificate. - With a client certificate set, the driver sends `X-ClickHouse-SSL-Certificate-Auth: on` and no password, and the server logs the user in by the certificate's common name (`ssl_certificates` in the user's configuration). - The crate's own TLS features stay off, so there is one TLS stack. +- With TLS off, a login the server drops, as the HTTPS port drops plain HTTP, is checked with a TLS handshake of its own, which sends no credential, and is reported as `TlsFailure::ServerRequiresTls` when the server completes it. ## Read-only diff --git a/linux/docs/drivers/mongodb.md b/linux/docs/drivers/mongodb.md index a2dac7ceba..e7d415cd25 100644 --- a/linux/docs/drivers/mongodb.md +++ b/linux/docs/drivers/mongodb.md @@ -104,10 +104,14 @@ Safe Mode reads statements the same way: Confirm Writes asks before every statem ## Trust +A new connection starts on `Disable`, as mongosh does for `mongodb://`, and on `VerifyFull` with a DNS seed list, as it does for `mongodb+srv://` ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). + The crate has no system store of its own: given no CA file it trusts only the Mozilla roots compiled into it. So where the crate does TLS, the driver hands it a bundle: the system store and the connection's CA file as one PEM (`tablepro_net::tls::ca_bundle_pem`), and the client certificate and key as one more, written mode 0600 into a private directory and removed once the client is built, which is when the crate reads them. The crate checks each server's certificate under that server's own name, so the server name override applies only through SSH (`ServerNameOverride::SshForwardOnly`). Require mode skips the check of the certificate and its name. Through SSH the driver does TLS around each stream with `tablepro_net::tls::build_client_config`, the platform verifier and the CA file, checked against `tls_server_name()`. `tests/system_trust.rs` measures both paths against a CA only the system store holds. +With TLS off and one host, direct or through SSH, a connect the server drops is checked with a TLS handshake of its own, which sends no credential, and is reported as `TlsFailure::ServerRequiresTls` when the server completes it. A seed list is not checked, since its host is not a server. + ## Server codes A server error keeps its code and name as `ServerCode::Mongo { code, name }`, such as `11000 DuplicateKey`. `AuthenticationFailed` (18) is an authentication failure, `MaxTimeMSExpired` (50) a timeout the server stopped, and `Interrupted` (11601), `InterruptedAtShutdown` (11600), `CursorKilled` (237), `QueryPlanKilled` (175) and `CursorNotFound` (43) the server acknowledging a stop. A value the text names that BSON cannot hold is `BadValue` (2), refused before it is sent. diff --git a/linux/docs/drivers/mysql.md b/linux/docs/drivers/mysql.md index 1622e1f09c..7993c32035 100644 --- a/linux/docs/drivers/mysql.md +++ b/linux/docs/drivers/mysql.md @@ -66,6 +66,8 @@ A save or a schema change runs in the server's own zone, `@@GLOBAL.time_zone`, a ## TLS +- A new connection starts on `Prefer`, as the mysql client's `--ssl-mode=PREFERRED` does ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). MariaDB's own client from 11.4 requires TLS and checks a self-signed certificate against the password, which sqlx cannot do, so MariaDB starts on `Prefer` too. +- `Prefer` is sqlx's `Preferred`: TLS when the server offers it, plaintext when it does not, and no certificate check. A handshake that fails after the server offered TLS is an error, as it is in the mysql client. - `Disable` connects without TLS. A server with `require_secure_transport` answers with error 3159, reported as `ServerRequiresTls`. MariaDB before 11.2 answers 1045, Access denied, as it does for a wrong password ([MDEV-30178](https://jira.mariadb.org/browse/MDEV-30178)), so on 10.11 the refusal reads as an authentication failure. - `Require` encrypts without checking the certificate. A server that does not offer TLS is reported as `ServerRefusedTls`. - `VerifyFull` is sqlx's `VerifyIdentity`. It trusts the system's CA store and the connection's CA file, which sqlx takes only as PEM, so the driver hands it both as one bundle; sqlx adds the Mozilla roots compiled into it ([Trust](../../../core/ARCHITECTURE.md#trust)). `Require` checks no certificate, so it loads neither. diff --git a/linux/docs/drivers/postgresql.md b/linux/docs/drivers/postgresql.md index 15167e3d4d..9cf90afcc2 100644 --- a/linux/docs/drivers/postgresql.md +++ b/linux/docs/drivers/postgresql.md @@ -19,10 +19,11 @@ A host that is an absolute path is the folder of a server on this computer, as l ## TLS -- `Disable` sends no SSLRequest. `Require` and `VerifyFull` both send it and refuse to continue in plaintext; they differ only in the certificate check. +- A new connection starts on `Prefer`, as libpq's `sslmode=prefer` does ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). +- `Disable` sends no SSLRequest. `Prefer` sends it, goes on in plaintext when the server answers `N`, and checks no certificate (tokio-postgres's `SslMode::Prefer`). Unlike libpq, it does not retry in plaintext after a handshake that fails. `Require` and `VerifyFull` both send it and refuse to continue in plaintext; they differ only in the certificate check. - `VerifyFull` trusts the system store plus the connection's CA file ([Trust](../../../core/ARCHITECTURE.md#trust)), and checks the name from `NetworkTarget::tls_server_name()`. - A client certificate is offered when one is set, for `cert` authentication in `pg_hba.conf`. -- A server that answers the SSLRequest with `N` is reported as `ServerRefusedTls`, never as a certificate problem: the TLS connector records whether the handshake started. +- Under `Require` or `VerifyFull`, a server that answers the SSLRequest with `N` is reported as `ServerRefusedTls`, never as a certificate problem: the TLS connector records whether the handshake started. - SCRAM channel binding (`tls-server-end-point`) is preferred, never required. It is used when the server's certificate is signed with RSA (SHA-1 to SHA-512) or ECDSA with SHA-256 or SHA-384. With any other signature, such as Ed25519 or ECDSA with SHA-512, tokio-postgres-rustls has no hash to bind with, and the login goes ahead without binding. ## Workspace calls diff --git a/linux/docs/drivers/redis.md b/linux/docs/drivers/redis.md index 8c0322d397..2d54ad9a1e 100644 --- a/linux/docs/drivers/redis.md +++ b/linux/docs/drivers/redis.md @@ -76,8 +76,14 @@ A key tab exports the rows it shows. An editor result's All Rows runs its comman ## Trust +A new connection starts on `Disable`, as redis-cli does without `--tls` ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). + TLS is rustls with aws-lc-rs from `tablepro_net::tls::build_client_config`, wrapped around the transport's stream with tokio-rustls, so an SSH forward carries it too. The certificate is checked against `tls_server_name()`, which the server name override can set on any route. A client certificate is presented when given; Redis does not map one to a user, and a server with `tls-auth-clients yes` refuses a client without one. Under TLS 1.3 that refusal arrives as an alert on the first read after the handshake, and the driver reports it as the TLS failure it is, not as a lost connection. +With TLS off, a login the server drops is checked with a TLS handshake of its own, which sends no credential, and is reported as `TlsFailure::ServerRequiresTls` when the server completes it. + +A server without TLS reads the TLS hello as a command and waits for its newline, so with TLS on the handshake times out. The driver then sends a plain `PING` on a stream of its own, and a RESP answer is reported as `TlsFailure::ServerRefusedTls`. + ## Server codes An error reply's first word is its code, kept as `ServerCode::Redis { prefix }` with the rest as the message. `WRONGPASS` and `NOAUTH` are an authentication failure, `READONLY` the server's read-only refusal, and `UNBLOCKED` the server acknowledging a stop. diff --git a/linux/docs/drivers/sql-server.md b/linux/docs/drivers/sql-server.md index 772817676f..39d2ce5ff0 100644 --- a/linux/docs/drivers/sql-server.md +++ b/linux/docs/drivers/sql-server.md @@ -24,6 +24,8 @@ An Azure SQL gateway or an availability group listener can answer a login with a ## TLS +A new connection starts on `VerifyFull`, as ODBC Driver 18, Microsoft.Data.SqlClient and SSMS do with `Encrypt=Mandatory` and `TrustServerCertificate=false` ([core ADR 0014](../../../core/docs/decisions/0014-tls-mode-of-a-new-connection.md)). A server with a certificate it made itself then reports `UnknownIssuer`, which its CA file or `Require` settles. There is no `Prefer`. + Up to `VerifyFull`, TLS is negotiated inside the TDS 7.4 pre-login exchange, after the server has said what encryption it supports. `Strict` is TDS 8.0: the TLS handshake comes first, with the ALPN protocol `tds/8.0`, and the pre-login and everything after it run inside it. | `TlsMode` | tiberius setting | Certificate check | diff --git a/linux/docs/error-handling.md b/linux/docs/error-handling.md index 8573039b0d..50667d0d59 100644 --- a/linux/docs/error-handling.md +++ b/linux/docs/error-handling.md @@ -106,14 +106,14 @@ A driver maps the codes the app acts on to their own variants and passes everyth ## `TlsFailure` and its remedies -Drivers classify a handshake failure with `tablepro_net::tls::classify`, which walks the error's sources to the rustls error. SQL Server reads rustls's message text instead, because tiberius keeps only the text. Where the driver can tell, a failure before the server agreed to TLS is `ServerRefusedTls`, never a certificate problem. +Drivers classify a handshake failure with `tablepro_net::tls::classify`, which walks the error's sources to the rustls error. SQL Server reads rustls's message text instead, because tiberius keeps only the text. Where the driver can tell, a failure before the server agreed to TLS is `ServerRefusedTls`, never a certificate problem. Under Disable, an engine that decides TLS by the port checks a plain login the server dropped with a TLS handshake of its own, sent with no credential, and reports a server that completes it as `ServerRequiresTls`. | `TlsFailure` | Cause | What the app offers | |---|---|---| | `UnknownIssuer` | The certificate's issuer is not in the trust set. | **Choose CA Certificate…**, which opens the connect dialog at the CA file row. | | `NameMismatch` | The certificate is for another name. | **Set TLS Server Name**, which opens the connect dialog at the server name row, where the route shows that row; MySQL over a direct route checks the host it dials and offers only **Edit Connection…**. | | `Expired`, `NotYetValid`, `Revoked` | The certificate itself is bad. | Nothing: the server's certificate has to be replaced. | -| `ServerRefusedTls` | The server does not speak TLS on this port. | The message; turn TLS off or use the TLS port. | +| `ServerRefusedTls` | The server does not speak TLS on this port. | **Change Encryption**, which opens the connect dialog at the Encryption row: Prefer or Disable reaches a server without TLS. | | `ServerRequiresTls` | TLS was off and the server insists on it. | **Change Encryption**, which opens the connect dialog at the Encryption row. | | `ServerRefusedStrict` | SQL Server closed a strict (TDS 8.0) login before answering: it does not speak TDS 8.0 (before 2022 on Windows, before 2025 on Linux) or has no certificate for it. | **Change Encryption**; Verify full suits an older server. | | `ServerRequiresStrict` | SQL Server closed a TDS 7.4 login before answering, as a server that requires strict encryption does. | **Change Encryption**, to Strict. | diff --git a/linux/docs/testing.md b/linux/docs/testing.md index 429e995687..126c6ec1ec 100644 --- a/linux/docs/testing.md +++ b/linux/docs/testing.md @@ -279,7 +279,7 @@ tablepro_test_support::tls_conformance_suite! { } ``` -The adapter (`TlsConformanceEngine`) gives the issuing and the unrelated CA file, the name on the server certificate and the error category a plaintext connect gets. The cases: Verify full with the issuing CA connects; with an unrelated CA it reports `UnknownIssuer`; with the wrong server name it reports `NameMismatch`; Require connects without a CA, and a CA file with Require is refused as a `ConfigError::CaFileUnsupported` before anything is sent; Disable against the TLS-only server is refused; against the same server started with a self-signed certificate (`start_self_signed`), Verify full on the system store alone reports `UnknownIssuer`, and trusting the server's own certificate (`server_certificate_file`) as the CA file connects. `client_identity: true` adds a case where the server requires the client certificate, through `ClientIdentityEngine`; SQL Server passes `false`. An engine whose server asks every client for a certificate or none names a second engine for that case with `identity_engine:`, as the Cassandra driver does, so the other cases run against a server that asks for none. MongoDB runs the suite twice, on a direct route, where the client library does TLS, and on a forward, where the driver's relay does. SQL Server adds its strict (TDS 8.0) cases in `tests/integration/strict.rs`: Strict reaches TDS 8.0 on 2025 and is refused as `ServerRefusedStrict` by 2017, 2019 and 2022, which on Linux closes a strict login, it checks the issuer, the name and a self-signed certificate as Verify full does, and against a 2025 server that requires it a TDS 7.4 login is `ServerRequiresStrict`. Every case needs Docker, and `tls_suite_flags_match_driver_capabilities` checks the flag against the driver's TLS capabilities without it. +The adapter (`TlsConformanceEngine`) gives the issuing and the unrelated CA file, the name on the server certificate and the error category a plaintext connect gets. The cases: Verify full with the issuing CA connects; with an unrelated CA it reports `UnknownIssuer`; with the wrong server name it reports `NameMismatch`; Require connects without a CA, and a CA file with Require is refused as a `ConfigError::CaFileUnsupported` before anything is sent; Disable against the TLS-only server is refused, as `ServerRequiresTls` where the engine reports it as a TLS failure; against the same server started with a self-signed certificate (`start_self_signed`), Verify full on the system store alone reports `UnknownIssuer`, and trusting the server's own certificate (`server_certificate_file`) as the CA file connects. `client_identity: true` adds a case where the server requires the client certificate, through `ClientIdentityEngine`; SQL Server passes `false`. An engine whose server asks every client for a certificate or none names a second engine for that case with `identity_engine:`, as the Cassandra driver does, so the other cases run against a server that asks for none. MongoDB runs the suite twice, on a direct route, where the client library does TLS, and on a forward, where the driver's relay does. SQL Server adds its strict (TDS 8.0) cases in `tests/integration/strict.rs`: Strict reaches TDS 8.0 on 2025 and is refused as `ServerRefusedStrict` by 2017, 2019 and 2022, which on Linux closes a strict login, it checks the issuer, the name and a self-signed certificate as Verify full does, and against a 2025 server that requires it a TDS 7.4 login is `ServerRequiresStrict`. Every case needs Docker, and `tls_suite_flags_match_driver_capabilities` checks the flag against the driver's TLS capabilities without it. ### Ignore reasons diff --git a/windows/src/TablePro.App.Model/ConnectionDraft.cs b/windows/src/TablePro.App.Model/ConnectionDraft.cs index 5804f94b58..17e606092b 100644 --- a/windows/src/TablePro.App.Model/ConnectionDraft.cs +++ b/windows/src/TablePro.App.Model/ConnectionDraft.cs @@ -38,6 +38,8 @@ public sealed class ConnectionDraft public bool SupportsClientIdentity { get; set; } + public ServerNameOverride ServerNameOverride { get; set; } = ServerNameOverride.Unsupported; + public string Name { get; set; } = string.Empty; public string Host { get; set; } = string.Empty; @@ -69,6 +71,9 @@ public sealed class ConnectionDraft public TlsMode TlsMode { get; set; } = TlsMode.Disable; + // A saved connection's mode was picked when it was saved; a new one follows the engine's default until the user picks. + public bool TlsModeChosen { get; set; } + public string CaFile { get; set; } = string.Empty; public string ServerName { get; set; } = string.Empty; @@ -93,6 +98,14 @@ public sealed class ConnectionDraft public bool UsesClientIdentity => SupportsClientIdentity && TlsMode != TlsMode.Disable; + // MySQL checks the host it dials, so another name works only where the dial goes through an SSH forward. + public bool ShowsServerName => VerifiesCertificate && ServerNameOverride switch + { + ServerNameOverride.AnyRoute => true, + ServerNameOverride.SshForwardOnly => UseSsh, + _ => false, + }; + public static ConnectionDraft New(DatabaseEngine engine) { ArgumentNullException.ThrowIfNull(engine); @@ -101,8 +114,10 @@ public static ConnectionDraft New(DatabaseEngine engine) EngineId = engine.Id, IsFileEngine = engine.DefaultPort is null, SupportsClientIdentity = engine.SupportsClientIdentity, + ServerNameOverride = engine.ServerNameOverride, Host = engine.DefaultPort is null ? string.Empty : "localhost", Port = engine.DefaultPort?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + TlsMode = engine.NewConnectionTls(engine.DefaultPort), }; } @@ -117,6 +132,7 @@ public static ConnectionDraft From(SavedConnection connection, DatabaseEngine en EngineId = connection.EngineId, IsFileEngine = engine.DefaultPort is null, SupportsClientIdentity = engine.SupportsClientIdentity, + ServerNameOverride = engine.ServerNameOverride, Name = connection.Name, Host = connection.Host, Port = connection.Port > 0 ? connection.Port.ToString(CultureInfo.InvariantCulture) : string.Empty, @@ -130,6 +146,7 @@ public static ConnectionDraft From(SavedConnection connection, DatabaseEngine en SshAuth = connection.Ssh?.Auth ?? SshAuthMethod.Agent, SshKeyPath = connection.Ssh?.KeyPath ?? string.Empty, TlsMode = connection.Tls.Mode, + TlsModeChosen = true, CaFile = connection.Tls.CaFile ?? string.Empty, ServerName = connection.Tls.ServerName ?? string.Empty, ClientCertificate = connection.Tls.ClientCertificate ?? string.Empty, @@ -149,14 +166,37 @@ public void Apply(ParsedConnectionUrl url, DatabaseEngine engine) EngineId = url.EngineId; IsFileEngine = engine.DefaultPort is null; SupportsClientIdentity = engine.SupportsClientIdentity; + ServerNameOverride = engine.ServerNameOverride; Host = url.Host; Port = (url.Port ?? engine.DefaultPort)?.ToString(CultureInfo.InvariantCulture) ?? string.Empty; UserName = url.UserName; Password = url.Password ?? Password; Database = url.Database; - if (url.TlsMode is { } mode) + // A mode the engine lacks, such as sslmode=prefer on SQL Server, leaves the engine's default. + if (url.TlsMode is { } mode && engine.SupportedTlsModes.Contains(mode)) { TlsMode = mode; + TlsModeChosen = true; + } + else + { + TlsModeChosen = false; + FollowTlsDefault(engine); + } + + CaFile = url.CaFile ?? CaFile; + ClientCertificate = url.ClientCertificate ?? ClientCertificate; + ClientKey = url.ClientKey ?? ClientKey; + ServerName = url.ServerName ?? ServerName; + } + + public void FollowTlsDefault(DatabaseEngine engine) + { + ArgumentNullException.ThrowIfNull(engine); + if (!TlsModeChosen || !engine.SupportedTlsModes.Contains(TlsMode)) + { + TlsMode = engine.NewConnectionTls(ParsePort(Port)); + TlsModeChosen = false; } CaFile = url.CaFile ?? CaFile; @@ -259,7 +299,7 @@ public SavedConnection ToConnection() VerifiesCertificate ? Blank(CaFile) : null, UsesClientIdentity ? Blank(ClientCertificate) : null, UsesClientIdentity ? Blank(ClientKey) : null, - VerifiesCertificate ? Blank(ServerName) : null), + ShowsServerName ? Blank(ServerName) : null), SafeMode, IntegratedAuth: IntegratedAuth, Ssh: UseSsh diff --git a/windows/src/TablePro.App.Model/TlsRemedy.cs b/windows/src/TablePro.App.Model/TlsRemedy.cs new file mode 100644 index 0000000000..3712f2b278 --- /dev/null +++ b/windows/src/TablePro.App.Model/TlsRemedy.cs @@ -0,0 +1,26 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum TlsRemedy +{ + ChooseCaCertificate, + SetServerName, + ChangeEncryption, +} + +public static class TlsRemedies +{ + // An expired or revoked certificate is the server's to replace, so it has no remedy here, nor has a name + // mismatch where the engine checks only the host it dials. + public static TlsRemedy? For(TlsFailure failure, bool serverNameShown) => failure switch + { + TlsFailure.UnknownIssuer => TlsRemedy.ChooseCaCertificate, + TlsFailure.NameMismatch when serverNameShown => TlsRemedy.SetServerName, + TlsFailure.ServerRefusedTls + or TlsFailure.ServerRequiresTls + or TlsFailure.ServerRefusedStrict + or TlsFailure.ServerRequiresStrict => TlsRemedy.ChangeEncryption, + _ => null, + }; +} diff --git a/windows/src/TablePro.App/ConnectionForm/ConnectionFormWindow.xaml b/windows/src/TablePro.App/ConnectionForm/ConnectionFormWindow.xaml index 2baf873daf..f6e3a2fc5e 100644 --- a/windows/src/TablePro.App/ConnectionForm/ConnectionFormWindow.xaml +++ b/windows/src/TablePro.App/ConnectionForm/ConnectionFormWindow.xaml @@ -124,7 +124,7 @@ - + @@ -195,7 +195,7 @@ - +