Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions core/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
71 changes: 69 additions & 2 deletions core/crates/core/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<LocalSocket> {
self.network_options.iter().find_map(|option| match option {
NetworkOption::LocalSocket(socket) => Some(*socket),
Expand All @@ -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(())
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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(())
Expand Down
9 changes: 5 additions & 4 deletions core/crates/core/src/connection_url/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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"),
Expand Down
14 changes: 7 additions & 7 deletions core/crates/core/src/connection_url/tls_hints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions core/crates/core/src/tls_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 13 additions & 1 deletion core/crates/core/src/tls_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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"),
Expand Down
24 changes: 24 additions & 0 deletions core/crates/core/src/tls_mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)]
Expand All @@ -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\"")
);
}
}
2 changes: 2 additions & 0 deletions core/crates/drivers/cassandra/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 25 additions & 3 deletions core/crates/drivers/cassandra/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -53,6 +53,7 @@ pub(crate) struct CqlEndpoint {
transport: Arc<dyn Transport>,
login: Option<(String, SecretString)>,
tls: Option<Arc<rustls::ClientConfig>>,
tls_server_name: String,
keyspace: Option<String>,
liveness: LivenessPolicy,
client_version: String,
Expand All @@ -69,14 +70,16 @@ 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?;
Ok(Self {
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(),
Expand Down Expand Up @@ -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,
};
Expand All @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions core/crates/drivers/cassandra/tests/integration/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,10 @@ impl<S: Server, const IDENTITY: bool> TlsConformanceEngine for CqlTlsEngine<S, I
}

/// A plaintext STARTUP fails the node's handshake, which closes the
/// connection without a CQL answer.
/// connection without a CQL answer, then completes the driver's own
/// TLS handshake.
fn plaintext_rejection_category(&self) -> ErrorCategory {
ErrorCategory::ConnectionLost
ErrorCategory::Tls
}
}

Expand Down
4 changes: 4 additions & 0 deletions core/crates/drivers/clickhouse/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading