diff --git a/seaweed-vector/Cargo.lock b/seaweed-vector/Cargo.lock index d454d0d39d..4e3ee9865c 100644 --- a/seaweed-vector/Cargo.lock +++ b/seaweed-vector/Cargo.lock @@ -6338,6 +6338,7 @@ dependencies = [ "protoc-bin-vendored", "reqwest 0.12.28", "rustls", + "rustls-native-certs", "seaweed-common", "thiserror 2.0.21", "tokio", diff --git a/seaweed-volume/src/config.rs b/seaweed-volume/src/config.rs index f091ee11de..93e106c858 100644 --- a/seaweed-volume/src/config.rs +++ b/seaweed-volume/src/config.rs @@ -1157,48 +1157,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon if trimmed.starts_with('#') || trimmed.is_empty() { continue; } - if trimmed == "[jwt.signing.read]" { - section = Section::JwtSigningRead; - continue; - } - if trimmed == "[jwt.signing]" { - section = Section::JwtSigning; - continue; - } - if trimmed == "[https.client]" { - section = Section::HttpsClient; - continue; - } - if trimmed == "[grpc]" { - section = Section::Grpc; - continue; - } - if trimmed == "[https.volume]" { - section = Section::HttpsVolume; - continue; - } - if trimmed == "[grpc.volume]" { - section = Section::GrpcVolume; - continue; - } - if trimmed == "[tls]" { - section = Section::Tls; - continue; - } - if trimmed == "[guard]" { - section = Section::Guard; - continue; - } - if trimmed == "[access]" { - section = Section::Access; - continue; - } - if trimmed == "[fips]" { - section = Section::Fips; - continue; - } - if trimmed.starts_with('[') { - section = Section::None; + if let Some(header) = section_header(trimmed) { + section = match header { + "[jwt.signing.read]" => Section::JwtSigningRead, + "[jwt.signing]" => Section::JwtSigning, + "[https.client]" => Section::HttpsClient, + "[grpc]" => Section::Grpc, + "[https.volume]" => Section::HttpsVolume, + "[grpc.volume]" => Section::GrpcVolume, + "[tls]" => Section::Tls, + "[guard]" => Section::Guard, + "[access]" => Section::Access, + "[fips]" => Section::Fips, + _ => Section::None, + }; continue; } @@ -1305,6 +1277,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon cfg } +/// The table header on a trimmed security.toml line, without the trailing +/// comment TOML allows after it (`[fips] # policy` is `[fips]`), or `None` +/// when the line is not a header. None of the sections read here has a `#` +/// in its name. +fn section_header(trimmed: &str) -> Option<&str> { + if !trimmed.starts_with('[') { + return None; + } + let header = trimmed + .split_once('#') + .map_or(trimmed, |(header, _)| header); + Some(header.trim_end()) +} + /// Reads the right-hand side of `key = value` the way TOML (and so Go) does: /// escapes decoded, literal strings kept as written, a trailing comment /// dropped. Text TOML rejects keeps the plain quote trimming. @@ -1343,8 +1329,26 @@ fn resolve_fips_setting_with_env( reason: e.to_string(), }); } - let file_value = parse_security_config_with_env(&path.to_string_lossy(), env).fips_mode; - seaweed_common::fips::resolve(Some(&path), file_value.as_deref(), env) + let parsed = parse_security_config_with_env(&path.to_string_lossy(), env); + fips_setting_from_parsed(path, &parsed, env) +} + +/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env` +/// applied. A parse that could not read the file is an error like the first +/// read, so a file that stops being readable between the two reads cannot +/// leave the mode off. +fn fips_setting_from_parsed( + path: PathBuf, + parsed: &SecurityConfig, + env: EnvLookup<'_>, +) -> Result { + if !parsed.file_read { + return Err(seaweed_common::fips::FipsModeError::File { + path, + reason: "could not be read".to_string(), + }); + } + seaweed_common::fips::resolve(Some(&path), parsed.fips_mode.as_deref(), env) } fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option { @@ -2339,6 +2343,24 @@ previous_key = "read-old" assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err()); } + #[test] + fn test_section_headers_with_a_trailing_comment() { + use seaweed_common::fips::FipsMode; + let tmp = tempfile::NamedTempFile::new().unwrap(); + let text = "[fips] # deployment policy\nmode = \"on\"\n\ + [jwt.signing] # comment\nkey = \"secret\"\n\ + [other] # not read\nkey = \"ignored\"\n"; + std::fs::write(tmp.path(), text).unwrap(); + let path = tmp.path().to_str().unwrap(); + assert!(text.parse::().is_ok(), "TOML, as Go reads it"); + + let cfg = parse_security_config_with_env(path, &fake_env(&[])); + assert_eq!(cfg.fips_mode.as_deref(), Some("on")); + assert_eq!(cfg.jwt_signing_key, b"secret"); + let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap(); + assert_eq!(setting.mode, FipsMode::On); + } + #[test] fn test_fips_mode_refuses_a_security_file_it_cannot_read() { let tmp = tempfile::NamedTempFile::new().unwrap(); @@ -2355,6 +2377,27 @@ previous_key = "read-old" assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off); } + #[test] + fn test_fips_mode_refuses_a_parse_that_did_not_read_the_file() { + use seaweed_common::fips::FipsMode; + let path = PathBuf::from("/etc/seaweedfs/security.toml"); + let unread = SecurityConfig::default(); + let err = fips_setting_from_parsed(path.clone(), &unread, &fake_env(&[])).unwrap_err(); + assert!( + err.to_string() + .contains("could not be read; cannot tell whether it sets fips.mode"), + "{err}" + ); + + let read = SecurityConfig { + file_read: true, + fips_mode: Some("on".to_string()), + ..SecurityConfig::default() + }; + let setting = fips_setting_from_parsed(path, &read, &fake_env(&[])).unwrap(); + assert_eq!(setting.mode, FipsMode::On); + } + #[test] fn test_env_override_takes_precedence_over_file() { let tmp = tempfile::NamedTempFile::new().unwrap(); diff --git a/seaweed-worker/Cargo.lock b/seaweed-worker/Cargo.lock index 06ef8e6cdb..69e8e89aeb 100644 --- a/seaweed-worker/Cargo.lock +++ b/seaweed-worker/Cargo.lock @@ -6363,6 +6363,7 @@ dependencies = [ "protoc-bin-vendored", "reqwest 0.12.28", "rustls", + "rustls-native-certs", "rustls-pemfile", "seaweed-common", "thiserror 2.0.20", diff --git a/seaweed-worker/crates/sw-client/Cargo.toml b/seaweed-worker/crates/sw-client/Cargo.toml index 17751b9b3a..677f256cf0 100644 --- a/seaweed-worker/crates/sw-client/Cargo.toml +++ b/seaweed-worker/crates/sw-client/Cargo.toml @@ -17,6 +17,9 @@ prost.workspace = true # System roots for volume servers behind public CAs, as Go's http client. reqwest = { version = "0.12", default-features = false, features = ["multipart", "rustls-tls-native-roots"] } rustls = { version = "0.23", default-features = false, features = ["ring"] } +# The system roots for the FIPS-mode client configuration sw-client builds +# itself; the version reqwest's rustls-tls-native-roots uses. +rustls-native-certs = "0.8" # The process-wide rustls provider every SeaweedFS Rust binary installs. seaweed-common = { path = "../../../seaweed-common" } thiserror = "2" diff --git a/seaweed-worker/crates/sw-client/src/transport.rs b/seaweed-worker/crates/sw-client/src/transport.rs index b8b66fe8e4..2735ec0068 100644 --- a/seaweed-worker/crates/sw-client/src/transport.rs +++ b/seaweed-worker/crates/sw-client/src/transport.rs @@ -238,9 +238,8 @@ impl HttpTransport { pub fn with_tls(tls: &HttpsTls) -> Result { install_crypto_provider(); let builder = reqwest::Client::builder().connect_timeout(VOLUME_CONNECT_TIMEOUT); - let builder = if tls.insecure_skip_verify && seaweed_common::fips::process_mode().is_fips() - { - builder.use_preconfigured_tls(unverified_tls_config( + let builder = if seaweed_common::fips::process_mode().is_fips() { + builder.use_preconfigured_tls(fips_tls_config( tls, Arc::new(seaweed_common::tls::crypto_provider()), )?) @@ -283,24 +282,31 @@ fn reqwest_tls(builder: reqwest::ClientBuilder, tls: &HttpsTls) -> Result, -) -> Result { - let verifier = Arc::new(UnverifiedServer { - provider: provider.clone(), - }); - let builder = rustls::ClientConfig::builder_with_provider(provider) +/// The client configuration for `tls` in FIPS mode, on `provider`. It is +/// built here rather than by reqwest for two reasons: reqwest leaves +/// `require_ems` at rustls's default, which is off for a provider that is not +/// FIPS-validated, while Go requires the Extended Master Secret for TLS 1.2 +/// in FIPS mode; and reqwest's verifier for `insecure_skip_verify` advertises +/// its own signature schemes (SHA-1, Ed448) whatever the provider allows. +/// Server certificates are checked against `ca` (the system roots without +/// one); with `insecure_skip_verify` they are not, but handshake signatures +/// still are, with the provider's algorithms, and only its schemes are +/// offered, and a malformed `ca` is still refused, as reqwest refuses it on +/// every path. HTTP/1.1 only, as the volume servers speak it. +fn fips_tls_config(tls: &HttpsTls, provider: Arc) -> Result { + let builder = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_safe_default_protocol_versions() - .context("TLS versions")? - .dangerous() - .with_custom_certificate_verifier(verifier); + .context("TLS versions")?; + let builder = if tls.insecure_skip_verify { + if let Some(ca) = &tls.ca_pem { + ca_roots(ca)?; + } + builder + .dangerous() + .with_custom_certificate_verifier(Arc::new(UnverifiedServer { provider })) + } else { + builder.with_root_certificates(root_certificates(tls)?) + }; let mut config = match (&tls.cert_pem, &tls.key_pem) { (Some(cert), Some(key)) => { let chain = CertificateDer::pem_slice_iter(cert) @@ -315,10 +321,47 @@ fn unverified_tls_config( _ => bail!("https.client needs both cert and key, or neither"), }; config.alpn_protocols = vec![b"http/1.1".to_vec()]; - config.require_ems = config.require_ems || seaweed_common::tls::require_ems(); + config.require_ems = true; Ok(config) } +/// The roots server certificates are checked against: the certificates in +/// `https.client.ca`, else the system's. +fn root_certificates(tls: &HttpsTls) -> Result { + match &tls.ca_pem { + Some(ca) => ca_roots(ca), + None => native_roots(), + } +} + +/// The certificates in an `https.client.ca` PEM, refused when one does not +/// parse, as reqwest refuses them. +fn ca_roots(ca: &[u8]) -> Result { + let mut roots = rustls::RootCertStore::empty(); + for cert in CertificateDer::pem_slice_iter(ca) { + roots + .add(cert.context("https.client.ca")?) + .context("https.client.ca")?; + } + Ok(roots) +} + +/// The system's root certificates as reqwest loads them: ones rustls cannot +/// parse are skipped, and it is an error only when none parses and some did +/// not. +fn native_roots() -> Result { + let loaded = rustls_native_certs::load_native_certs(); + let mut roots = rustls::RootCertStore::empty(); + let (added, ignored) = roots.add_parsable_certificates(loaded.certs); + if added == 0 && ignored > 0 { + bail!( + "no valid certificate in the system root store: {:?}", + loaded.errors + ); + } + Ok(roots) +} + /// Accepts any server certificate and host name, as `insecure_skip_verify` /// asks, while verifying the handshake signatures with the provider's /// algorithms and offering only their schemes. @@ -573,31 +616,148 @@ mod tests { recorder.0.lock().unwrap().clone() } - #[test] - fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() { - let provider = Arc::new(seaweed_common::tls::provider_for( + /// The provider FIPS mode installs. + fn fips_provider() -> Arc { + Arc::new(seaweed_common::tls::provider_for( seaweed_common::fips::FipsMode::On, - )); - let config = unverified_tls_config(&HttpsTls::default(), provider).unwrap(); - let mut offered = offered_schemes(config); + )) + } + + /// `https.client` with certificate checks off, as FIPS mode builds it. + fn unverified() -> HttpsTls { + HttpsTls { + insecure_skip_verify: true, + ..HttpsTls::default() + } + } + + /// `https.client` with `ca` set to the lance test CA. + fn with_test_ca() -> HttpsTls { + HttpsTls { + ca_pem: Some(TEST_CA.to_vec()), + ..HttpsTls::default() + } + } + + const TEST_CA: &[u8] = include_bytes!("../../lance/tests/tls/ca.pem"); + const TEST_LEAF: &[u8] = include_bytes!("../../lance/tests/tls/a.pem"); + const TEST_LEAF_KEY: &[u8] = include_bytes!("../../lance/tests/tls/a.key"); + + /// Runs a full handshake between `config` and a server presenting the + /// lance test leaf for `localhost`, in memory. + fn handshake(config: rustls::ClientConfig) -> std::result::Result<(), rustls::Error> { + let chain = CertificateDer::pem_slice_iter(TEST_LEAF) + .collect::, _>>() + .unwrap(); + let key = PrivateKeyDer::from_pem_slice(TEST_LEAF_KEY).unwrap(); + let server_config = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::aws_lc_rs::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(chain, key) + .unwrap(); + let name = ServerName::try_from("localhost").unwrap(); + let mut client = rustls::ClientConnection::new(Arc::new(config), name).unwrap(); + let mut server = rustls::ServerConnection::new(Arc::new(server_config)).unwrap(); + while client.is_handshaking() || server.is_handshaking() { + let mut flight = Vec::new(); + client.write_tls(&mut flight).unwrap(); + if !flight.is_empty() { + server.read_tls(&mut flight.as_slice()).unwrap(); + server.process_new_packets()?; + } + let mut flight = Vec::new(); + server.write_tls(&mut flight).unwrap(); + if !flight.is_empty() { + client.read_tls(&mut flight.as_slice()).unwrap(); + client.process_new_packets()?; + } + } + Ok(()) + } + + /// `offered` and the FIPS signature schemes, each sorted. + fn sorted_against_fips( + mut offered: Vec, + ) -> (Vec, Vec) { let mut want = seaweed_common::tls::FIPS_SIGNATURE_SCHEMES.to_vec(); offered.sort_by_key(|s| u16::from(*s)); want.sort_by_key(|s| u16::from(*s)); + (offered, want) + } + + #[test] + fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() { + let config = fips_tls_config(&unverified(), fips_provider()).unwrap(); + assert!(config.require_ems); + let (offered, want) = sorted_against_fips(offered_schemes(config)); assert_eq!(offered, want); assert!(!offered.contains(&SignatureScheme::ED448)); assert!(!offered.contains(&SignatureScheme::RSA_PKCS1_SHA1)); } #[test] - fn unverified_tls_needs_both_halves_of_the_identity() { - let provider = Arc::new(seaweed_common::tls::provider_for( - seaweed_common::fips::FipsMode::On, - )); - let half = HttpsTls { - cert_pem: Some(b"x".to_vec()), + fn verified_tls_in_fips_mode_requires_ems_and_checks_the_server() { + let config = fips_tls_config(&with_test_ca(), fips_provider()).unwrap(); + assert!(config.require_ems); + let (offered, want) = sorted_against_fips(offered_schemes(config.clone())); + assert_eq!(offered, want); + handshake(config).unwrap(); + + let wrong_ca = HttpsTls { + ca_pem: Some(TEST_LEAF.to_vec()), ..HttpsTls::default() }; - assert!(unverified_tls_config(&half, provider).is_err()); + let config = fips_tls_config(&wrong_ca, fips_provider()).unwrap(); + let err = handshake(config).unwrap_err(); + assert!( + matches!(err, rustls::Error::InvalidCertificate(_)), + "{err:?}" + ); + } + + /// A PEM certificate block whose DER is not a certificate. + const MALFORMED_CA: &[u8] = b"-----BEGIN CERTIFICATE----- +AAAA +-----END CERTIFICATE----- +"; + + #[test] + fn a_malformed_ca_is_refused_with_and_without_certificate_checks() { + for insecure_skip_verify in [false, true] { + let tls = HttpsTls { + ca_pem: Some(MALFORMED_CA.to_vec()), + insecure_skip_verify, + ..HttpsTls::default() + }; + let err = fips_tls_config(&tls, fips_provider()).unwrap_err(); + assert!(format!("{err:#}").contains("https.client.ca"), "{err:#}"); + assert!( + HttpTransport::with_tls(&tls).is_err(), + "off mode, insecure_skip_verify = {insecure_skip_verify}" + ); + } + let tls = HttpsTls { + ca_pem: Some(TEST_CA.to_vec()), + ..unverified() + }; + assert!(fips_tls_config(&tls, fips_provider()).is_ok()); + } + + #[test] + fn fips_tls_needs_both_halves_of_the_identity() { + let half = HttpsTls { + cert_pem: Some(b"x".to_vec()), + ..unverified() + }; + assert!(fips_tls_config(&half, fips_provider()).is_err()); + let half = HttpsTls { + cert_pem: Some(b"x".to_vec()), + ..with_test_ca() + }; + assert!(fips_tls_config(&half, fips_provider()).is_err()); } #[test]