Skip to main content

datadog_agent_commons/ipc/
tls.rs

1//! TLS helpers for client- and server-side IPC usage.
2
3use std::{
4    path::Path,
5    sync::Arc,
6    time::{Duration, Instant},
7};
8
9use rustls::{
10    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
11    crypto::CryptoProvider,
12    pki_types::{CertificateDer, ServerName, UnixTime},
13    server::danger::{ClientCertVerified, ClientCertVerifier},
14    version::{TLS12, TLS13},
15    CertificateError, ClientConfig, DigitallySignedStruct, DistinguishedName, ServerConfig, SignatureScheme,
16    SupportedProtocolVersion,
17};
18use rustls_pki_types::{pem::PemObject as _, PrivateKeyDer};
19use saluki_error::{generic_error, ErrorContext as _, GenericError};
20use saluki_tls::{ensure_client_config_fips_compliant, ensure_server_config_fips_compliant};
21
22const DEFAULT_CERT_READ_TIMEOUT: Duration = Duration::from_secs(20);
23const DEFAULT_CERT_READ_INTERVAL: Duration = Duration::from_millis(100);
24const IPC_TLS13_ONLY: &[&SupportedProtocolVersion] = &[&TLS13];
25const IPC_TLS12_ONLY: &[&SupportedProtocolVersion] = &[&TLS12];
26
27#[derive(Debug)]
28struct DatadogAgentServerCertVerifier {
29    cert: CertificateDer<'static>,
30    provider: Arc<CryptoProvider>,
31}
32
33impl DatadogAgentServerCertVerifier {
34    fn from_certificate_and_provider(cert: CertificateDer<'static>, provider: Arc<CryptoProvider>) -> Self {
35        Self { cert, provider }
36    }
37}
38
39impl ServerCertVerifier for DatadogAgentServerCertVerifier {
40    fn verify_server_cert(
41        &self, end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _server_name: &ServerName<'_>,
42        _ocsp_response: &[u8], _now: UnixTime,
43    ) -> Result<ServerCertVerified, rustls::Error> {
44        // Exact leaf DER equality pins one server identity; certificate chains and CA semantics do not broaden trust.
45        if end_entity != &self.cert {
46            return Err(rustls::Error::InvalidCertificate(CertificateError::UnknownIssuer));
47        }
48
49        Ok(ServerCertVerified::assertion())
50    }
51
52    fn verify_tls12_signature(
53        &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct,
54    ) -> Result<HandshakeSignatureValid, rustls::Error> {
55        rustls::crypto::verify_tls12_signature(message, cert, dss, &self.provider.signature_verification_algorithms)
56    }
57
58    fn verify_tls13_signature(
59        &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct,
60    ) -> Result<HandshakeSignatureValid, rustls::Error> {
61        rustls::crypto::verify_tls13_signature(message, cert, dss, &self.provider.signature_verification_algorithms)
62    }
63
64    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
65        self.provider.signature_verification_algorithms.supported_schemes()
66    }
67}
68
69#[derive(Debug)]
70struct DatadogAgentClientCertVerifier {
71    cert: CertificateDer<'static>,
72    provider: Arc<CryptoProvider>,
73}
74
75impl DatadogAgentClientCertVerifier {
76    fn from_certificate_and_provider(cert: CertificateDer<'static>, provider: Arc<CryptoProvider>) -> Self {
77        Self { cert, provider }
78    }
79}
80
81impl ClientCertVerifier for DatadogAgentClientCertVerifier {
82    fn offer_client_auth(&self) -> bool {
83        true
84    }
85
86    fn client_auth_mandatory(&self) -> bool {
87        true
88    }
89
90    fn root_hint_subjects(&self) -> &[DistinguishedName] {
91        &[]
92    }
93
94    fn verify_client_cert(
95        &self, end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _now: UnixTime,
96    ) -> Result<ClientCertVerified, rustls::Error> {
97        if end_entity != &self.cert {
98            return Err(rustls::Error::InvalidCertificate(CertificateError::UnknownIssuer));
99        }
100
101        Ok(ClientCertVerified::assertion())
102    }
103
104    fn verify_tls12_signature(
105        &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct,
106    ) -> Result<HandshakeSignatureValid, rustls::Error> {
107        rustls::crypto::verify_tls12_signature(message, cert, dss, &self.provider.signature_verification_algorithms)
108    }
109
110    fn verify_tls13_signature(
111        &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct,
112    ) -> Result<HandshakeSignatureValid, rustls::Error> {
113        rustls::crypto::verify_tls13_signature(message, cert, dss, &self.provider.signature_verification_algorithms)
114    }
115
116    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
117        self.provider.signature_verification_algorithms.supported_schemes()
118    }
119}
120
121/// Builds an exact shared-certificate mTLS client configuration for Datadog Agent IPC.
122///
123/// The client accepts only a server leaf certificate whose DER encoding exactly matches the configured IPC certificate
124/// and verifies the handshake signature as proof that the server possesses its private key. The client presents the same
125/// certificate and proves possession of its private key to satisfy mandatory server-side client authentication.
126/// Certificate chains and CA trust do not broaden the accepted server identity.
127///
128/// # Errors
129///
130/// If the IPC TLS identity file cannot be read or does not contain a valid PEM-encoded certificate and private key, an
131/// error is returned.
132pub async fn build_ipc_client_ipc_tls_config<P: AsRef<Path>>(cert_path: P) -> Result<ClientConfig, GenericError> {
133    // Read the certificate file, and extract the certificate and private key from it.
134    let (parsed_cert, parsed_key) = read_and_parse_certificate_file(
135        cert_path.as_ref(),
136        DEFAULT_CERT_READ_TIMEOUT,
137        DEFAULT_CERT_READ_INTERVAL,
138    )
139    .await?;
140
141    let crypto_provider = rustls::crypto::CryptoProvider::get_default()
142        .map(Arc::clone)
143        .ok_or_else(|| generic_error!("Default cryptography provider not yet installed."))?;
144
145    build_ipc_client_tls_config_with_provider(parsed_cert, parsed_key, crypto_provider).with_error_context(|| {
146        format!(
147            "Failed to build client TLS configuration from certificate file '{}'.",
148            cert_path.as_ref().display()
149        )
150    })
151}
152
153/// Builds the IPC client configuration from a parsed identity and an explicit cryptography provider.
154fn build_ipc_client_tls_config_with_provider(
155    cert: CertificateDer<'static>, key: PrivateKeyDer<'static>, provider: Arc<CryptoProvider>,
156) -> Result<ClientConfig, GenericError> {
157    // Create our custom certificate verifier to use the parsed certificate for server verification.
158    let agent_cert_verifier = Arc::new(DatadogAgentServerCertVerifier::from_certificate_and_provider(
159        cert.clone(),
160        Arc::clone(&provider),
161    ));
162
163    let protocol_versions = ipc_client_protocol_versions(&provider);
164    let config = ClientConfig::builder_with_provider(provider)
165        .with_protocol_versions(protocol_versions)
166        .error_context("Failed to select TLS protocol versions.")?
167        .dangerous()
168        .with_custom_certificate_verifier(agent_cert_verifier)
169        .with_client_auth_cert(vec![cert], key)
170        .error_context("Failed to set the client certificate.")?;
171
172    ensure_client_config_fips_compliant(&config)?;
173
174    Ok(config)
175}
176
177/// Returns the TLS protocol versions that the IPC client offers with the given cryptography provider.
178///
179/// The client offers only TLS 1.3 when the provider has a TLS 1.3 cipher suite. Otherwise, it offers only TLS 1.2. For
180/// example, the Windows CNG provider in FIPS mode has no TLS 1.3 cipher suites on Windows Server 2016, because CNG
181/// there has no HKDF algorithm. Its TLS 1.2 cipher suites use the CNG TLS 1.2 key derivation function, which is
182/// available in FIPS mode.
183///
184/// The TLS 1.2 fallback relies on the Datadog Agent's IPC server accepting TLS 1.2. Its server configuration sets no
185/// minimum version, so Go's default minimum of TLS 1.2 applies:
186/// <https://github.com/DataDog/datadog-agent/blob/a04e8aa6d8a46856d37cfbe064dd936d1e214701/pkg/api/security/cert/cert_getter.go#L179-L185>
187fn ipc_client_protocol_versions(provider: &CryptoProvider) -> &'static [&'static SupportedProtocolVersion] {
188    if provider.cipher_suites.iter().any(|suite| suite.tls13().is_some()) {
189        IPC_TLS13_ONLY
190    } else {
191        IPC_TLS12_ONLY
192    }
193}
194
195/// Builds an exact shared-certificate mTLS server configuration for Datadog Agent IPC.
196///
197/// The server requires every client to present a leaf certificate whose DER encoding exactly matches the configured IPC
198/// certificate and to prove possession of its private key with the handshake signature. The server presents the same
199/// certificate as its identity. Certificate chains and CA trust do not broaden the accepted client identity, and no
200/// overlap between different certificates is accepted.
201///
202/// # Errors
203///
204/// If the IPC TLS identity file cannot be read or does not contain a valid PEM-encoded certificate and private key, an
205/// error is returned.
206pub async fn build_ipc_server_tls_config<P: AsRef<Path>>(cert_path: P) -> Result<ServerConfig, GenericError> {
207    // Read the certificate file, and extract the certificate and private key from it.
208    let (parsed_cert, parsed_key) = read_and_parse_certificate_file(
209        cert_path.as_ref(),
210        DEFAULT_CERT_READ_TIMEOUT,
211        DEFAULT_CERT_READ_INTERVAL,
212    )
213    .await?;
214
215    let crypto_provider = rustls::crypto::CryptoProvider::get_default()
216        .map(Arc::clone)
217        .ok_or_else(|| generic_error!("Default cryptography provider not yet installed."))?;
218    let agent_cert_verifier = Arc::new(DatadogAgentClientCertVerifier::from_certificate_and_provider(
219        parsed_cert.clone(),
220        crypto_provider,
221    ));
222
223    let mut config = ServerConfig::builder()
224        .with_client_cert_verifier(agent_cert_verifier)
225        .with_single_cert(vec![parsed_cert], parsed_key)
226        .with_error_context(|| {
227            format!(
228                "Failed to build server TLS configuration from certificate file '{}'.",
229                cert_path.as_ref().display()
230            )
231        })?;
232
233    ensure_server_config_fips_compliant(&mut config)?;
234
235    Ok(config)
236}
237
238/// Reads and parses a certificate file from the given path with retry behavior.
239///
240/// If reading the file fails, it will retry reading it for up to `timeout` total, waiting `interval` between attempts,
241/// until it succeeds or the timeout is reached.
242///
243/// ## Errors
244///
245/// If the file can't be read after the maximum number of retries, or if the file isn't a valid certificate,
246/// an error will be returned.
247async fn read_and_parse_certificate_file(
248    cert_path: &Path, timeout: Duration, interval: Duration,
249) -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), GenericError> {
250    if timeout < interval {
251        return Err(generic_error!(
252            "Timeout is less than interval ({} <  {}).",
253            timeout.as_secs(),
254            interval.as_secs()
255        ));
256    }
257
258    let start_time = Instant::now();
259    let mut last_error = String::new();
260    while start_time.elapsed() < timeout {
261        match tokio::fs::read(cert_path).await {
262            Ok(raw_cert_data) => {
263                let parsed_cert = CertificateDer::from_pem_slice(&raw_cert_data[..])
264                    .with_error_context(|| format!("Failed to parse certificate file '{}'.", cert_path.display()))?
265                    .into_owned();
266
267                let parsed_key = PrivateKeyDer::from_pem_slice(&raw_cert_data[..])
268                    .with_error_context(|| format!("Failed to parse private key file '{}'.", cert_path.display()))?
269                    .clone_key();
270
271                return Ok((parsed_cert, parsed_key));
272            }
273            Err(e) => {
274                last_error = e.to_string();
275                tokio::time::sleep(interval).await;
276            }
277        }
278    }
279
280    Err(generic_error!(
281        "Failed to read certificate file '{}' after {} seconds: {}",
282        cert_path.display(),
283        timeout.as_secs(),
284        last_error
285    ))
286}
287
288#[cfg(test)]
289mod tests {
290    use std::{fs, io, path::PathBuf, sync::Arc, time::Duration};
291
292    use rcgen::{generate_simple_self_signed, CertifiedKey};
293    use rustls::{
294        crypto::CryptoProvider,
295        pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName},
296        version::{TLS12, TLS13},
297        ClientConfig, ProtocolVersion, ServerConfig,
298    };
299    use tempfile::TempDir;
300    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
301    use tokio_rustls::{TlsAcceptor, TlsConnector};
302
303    use super::{
304        build_ipc_client_ipc_tls_config, build_ipc_client_tls_config_with_provider, build_ipc_server_tls_config,
305        ipc_client_protocol_versions, DatadogAgentServerCertVerifier,
306    };
307
308    const APPLICATION_BYTE: u8 = 42;
309    const TEST_TIMEOUT: Duration = Duration::from_secs(5);
310
311    struct TestIdentity {
312        _temp_dir: TempDir,
313        cert_path: PathBuf,
314        cert_der: CertificateDer<'static>,
315        key_der: Vec<u8>,
316    }
317
318    impl TestIdentity {
319        fn localhost() -> Self {
320            let CertifiedKey { cert, signing_key } = generate_simple_self_signed(["localhost".to_owned()])
321                .expect("self-signed localhost certificate should be generated");
322            let temp_dir = tempfile::tempdir().expect("temporary certificate directory should be created");
323            let cert_path = temp_dir.path().join("ipc-cert.pem");
324            fs::write(&cert_path, format!("{}{}", cert.pem(), signing_key.serialize_pem()))
325                .expect("certificate and private key should be written");
326
327            Self {
328                _temp_dir: temp_dir,
329                cert_path,
330                cert_der: cert.der().clone(),
331                key_der: signing_key.serialize_der(),
332            }
333        }
334
335        fn private_key(&self) -> PrivateKeyDer<'static> {
336            PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(self.key_der.clone()))
337        }
338    }
339
340    fn initialize_crypto_provider() {
341        let _ = saluki_tls::initialize_default_crypto_provider();
342        assert!(
343            CryptoProvider::get_default().is_some(),
344            "default crypto provider should be installed"
345        );
346    }
347
348    fn client_config_pinned_to(server_identity: &TestIdentity, client_identity: Option<&TestIdentity>) -> ClientConfig {
349        let provider = CryptoProvider::get_default()
350            .cloned()
351            .expect("default crypto provider should be installed");
352        let verifier = Arc::new(DatadogAgentServerCertVerifier::from_certificate_and_provider(
353            server_identity.cert_der.clone(),
354            provider,
355        ));
356        let builder = ClientConfig::builder_with_protocol_versions(&[&TLS13])
357            .dangerous()
358            .with_custom_certificate_verifier(verifier);
359
360        match client_identity {
361            Some(identity) => builder
362                .with_client_auth_cert(vec![identity.cert_der.clone()], identity.private_key())
363                .expect("client TLS config should accept generated identity"),
364            None => builder.with_no_client_auth(),
365        }
366    }
367
368    async fn accept_client(server_config: ServerConfig, client_config: ClientConfig) -> io::Result<u8> {
369        tokio::time::timeout(TEST_TIMEOUT, async move {
370            let (client_io, server_io) = tokio::io::duplex(4096);
371            let client = async move {
372                let connector = TlsConnector::from(Arc::new(client_config));
373                let server_name = ServerName::try_from("localhost").expect("localhost should be a valid server name");
374                let mut stream = connector.connect(server_name, client_io).await?;
375                stream.write_u8(APPLICATION_BYTE).await?;
376                Ok::<_, io::Error>(stream)
377            };
378            let server = async move {
379                let acceptor = TlsAcceptor::from(Arc::new(server_config));
380                let mut stream = acceptor.accept(server_io).await?;
381                Ok(stream
382                    .read_u8()
383                    .await
384                    .expect("accepted client should send an application byte"))
385            };
386
387            let (_, server_result) = tokio::join!(client, server);
388            server_result
389        })
390        .await
391        .expect("TLS handshake should not time out")
392    }
393
394    #[tokio::test]
395    async fn matching_ipc_identity_completes_mtls_and_delivers_application_byte() {
396        initialize_crypto_provider();
397        let identity_a = TestIdentity::localhost();
398        let server_config = build_ipc_server_tls_config(&identity_a.cert_path)
399            .await
400            .expect("production server TLS config should build");
401        let client_config = build_ipc_client_ipc_tls_config(&identity_a.cert_path)
402            .await
403            .expect("production client TLS config should build");
404
405        assert_eq!(
406            accept_client(server_config, client_config)
407                .await
408                .expect("server should accept the matching client identity"),
409            APPLICATION_BYTE
410        );
411    }
412
413    /// Returns the default provider without its TLS 1.3 cipher suites, like the Windows CNG provider in FIPS mode on a
414    /// host whose CNG has no HKDF algorithm.
415    fn provider_without_tls13_suites() -> Arc<CryptoProvider> {
416        let mut provider = CryptoProvider::get_default()
417            .map(|provider| provider.as_ref().clone())
418            .expect("default crypto provider should be installed");
419        provider.cipher_suites.retain(|suite| suite.tls13().is_none());
420        assert!(
421            !provider.cipher_suites.is_empty(),
422            "default crypto provider should have TLS 1.2 cipher suites"
423        );
424        Arc::new(provider)
425    }
426
427    #[test]
428    fn ipc_client_offers_only_tls13_when_provider_has_tls13_suites() {
429        initialize_crypto_provider();
430        let provider = CryptoProvider::get_default().expect("default crypto provider should be installed");
431
432        assert_eq!(ipc_client_protocol_versions(provider), &[&TLS13]);
433    }
434
435    #[test]
436    fn ipc_client_offers_only_tls12_when_provider_has_no_tls13_suites() {
437        initialize_crypto_provider();
438
439        assert_eq!(
440            ipc_client_protocol_versions(&provider_without_tls13_suites()),
441            &[&TLS12]
442        );
443    }
444
445    #[tokio::test]
446    async fn ipc_client_without_tls13_suites_completes_mtls_over_tls12() {
447        initialize_crypto_provider();
448        let identity = TestIdentity::localhost();
449        let server_config = build_ipc_server_tls_config(&identity.cert_path)
450            .await
451            .expect("production server TLS config should build");
452        let client_config = build_ipc_client_tls_config_with_provider(
453            identity.cert_der.clone(),
454            identity.private_key(),
455            provider_without_tls13_suites(),
456        )
457        .expect("client TLS config should build without TLS 1.3 cipher suites");
458
459        // FIPS 140-3 requires the Extended Master Secret extension for TLS 1.2. Rustls requires it whenever the
460        // provider reports FIPS, and the FIPS check that the builder runs depends on it.
461        assert_eq!(
462            client_config.require_ems,
463            client_config.crypto_provider().fips(),
464            "client should require Extended Master Secret exactly when the provider is FIPS"
465        );
466        assert_eq!(
467            server_config.require_ems,
468            server_config.crypto_provider().fips(),
469            "server should require Extended Master Secret exactly when the provider is FIPS"
470        );
471
472        let negotiated = tokio::time::timeout(TEST_TIMEOUT, async move {
473            let (client_io, server_io) = tokio::io::duplex(4096);
474            let client = async move {
475                let connector = TlsConnector::from(Arc::new(client_config));
476                let server_name = ServerName::try_from("localhost").expect("localhost should be a valid server name");
477                let mut stream = connector.connect(server_name, client_io).await?;
478                stream.write_u8(APPLICATION_BYTE).await?;
479                Ok::<_, io::Error>(stream.get_ref().1.protocol_version())
480            };
481            let server = async move {
482                let acceptor = TlsAcceptor::from(Arc::new(server_config));
483                let mut stream = acceptor.accept(server_io).await?;
484                stream.read_u8().await
485            };
486
487            let (client_result, server_result) = tokio::join!(client, server);
488            assert_eq!(
489                server_result.expect("server should accept the client over TLS 1.2"),
490                APPLICATION_BYTE
491            );
492            client_result.expect("client should connect over TLS 1.2")
493        })
494        .await
495        .expect("TLS handshake should not time out");
496
497        assert_eq!(negotiated, Some(ProtocolVersion::TLSv1_2));
498    }
499
500    #[tokio::test]
501    async fn missing_or_mismatched_client_certificate_makes_server_accept_fail() {
502        initialize_crypto_provider();
503        let identity_a = TestIdentity::localhost();
504        let server_config = build_ipc_server_tls_config(&identity_a.cert_path)
505            .await
506            .expect("production server TLS config should build");
507        let client_config = client_config_pinned_to(&identity_a, None);
508
509        accept_client(server_config, client_config)
510            .await
511            .expect_err("server accept should reject a missing client certificate");
512
513        let identity_b = TestIdentity::localhost();
514        let server_config = build_ipc_server_tls_config(&identity_a.cert_path)
515            .await
516            .expect("production server TLS config should build");
517        let client_config = client_config_pinned_to(&identity_a, Some(&identity_b));
518
519        accept_client(server_config, client_config)
520            .await
521            .expect_err("server accept should reject a different client certificate");
522    }
523}