Skip to main content

libp2p_tls/
lib.rs

1// Copyright 2021 Parity Technologies (UK) Ltd.
2// Copyright 2022 Protocol Labs.
3//
4// Permission is hereby granted, free of charge, to any person obtaining a
5// copy of this software and associated documentation files (the "Software"),
6// to deal in the Software without restriction, including without limitation
7// the rights to use, copy, modify, merge, publish, distribute, sublicense,
8// and/or sell copies of the Software, and to permit persons to whom the
9// Software is furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20// DEALINGS IN THE SOFTWARE.
21
22//! TLS configuration based on libp2p TLS specs.
23//!
24//! See <https://github.com/libp2p/specs/blob/master/tls/tls.md>.
25
26#![cfg_attr(docsrs, feature(doc_cfg))]
27
28pub mod certificate;
29mod upgrade;
30mod verifier;
31
32use std::sync::Arc;
33
34use certificate::AlwaysResolvesCert;
35pub use futures_rustls::TlsStream;
36use libp2p_identity::{Keypair, PeerId};
37pub use upgrade::{Config, UpgradeError};
38
39const P2P_ALPN: [u8; 6] = *b"libp2p";
40
41/// Create a TLS client configuration for libp2p.
42pub fn make_client_config(
43    keypair: &Keypair,
44    remote_peer_id: Option<PeerId>,
45) -> Result<rustls::ClientConfig, certificate::GenError> {
46    let (certificate, private_key) = certificate::generate(keypair)?;
47
48    let mut provider = rustls::crypto::aws_lc_rs::default_provider();
49    provider.cipher_suites = verifier::CIPHERSUITES.to_vec();
50
51    let cert_resolver = Arc::new(
52        AlwaysResolvesCert::new(certificate, &private_key)
53            .expect("Client cert key DER is valid; qed"),
54    );
55
56    let mut crypto = rustls::ClientConfig::builder_with_provider(provider.into())
57        .with_protocol_versions(verifier::PROTOCOL_VERSIONS)
58        .expect("Cipher suites and kx groups are configured; qed")
59        .dangerous()
60        .with_custom_certificate_verifier(Arc::new(
61            verifier::Libp2pCertificateVerifier::with_remote_peer_id(remote_peer_id),
62        ))
63        .with_client_cert_resolver(cert_resolver);
64    crypto.alpn_protocols = vec![P2P_ALPN.to_vec()];
65    crypto.key_log = Arc::new(rustls::KeyLogFile::new());
66
67    Ok(crypto)
68}
69
70/// Create a TLS server configuration for libp2p.
71pub fn make_server_config(
72    keypair: &Keypair,
73) -> Result<rustls::ServerConfig, certificate::GenError> {
74    let (certificate, private_key) = certificate::generate(keypair)?;
75
76    let mut provider = rustls::crypto::aws_lc_rs::default_provider();
77    provider.cipher_suites = verifier::CIPHERSUITES.to_vec();
78
79    let cert_resolver = Arc::new(
80        AlwaysResolvesCert::new(certificate, &private_key)
81            .expect("Server cert key DER is valid; qed"),
82    );
83
84    let mut crypto = rustls::ServerConfig::builder_with_provider(provider.into())
85        .with_protocol_versions(verifier::PROTOCOL_VERSIONS)
86        .expect("Cipher suites and kx groups are configured; qed")
87        .with_client_cert_verifier(Arc::new(verifier::Libp2pCertificateVerifier::new()))
88        .with_cert_resolver(cert_resolver);
89    crypto.alpn_protocols = vec![P2P_ALPN.to_vec()];
90    crypto.key_log = Arc::new(rustls::KeyLogFile::new());
91
92    Ok(crypto)
93}
94
95#[cfg(test)]
96mod tests {
97    use rustls::NamedGroup;
98
99    use super::*;
100
101    #[test]
102    fn prefers_x25519_mlkem768() {
103        let keypair = Keypair::generate_ed25519();
104        let config = make_client_config(&keypair, None).unwrap();
105
106        assert_eq!(
107            config.crypto_provider().kx_groups[0].name(),
108            NamedGroup::X25519MLKEM768
109        );
110    }
111}