Skip to main content

smgw_sec/
transport.rs

1//! Pinned mutual TLS over loopback for the smart meter gateway simulators.
2//!
3//! The synthetic CLS and management sessions use a TLS 1.2 Brainpool profile.
4//! Each endpoint receives its own identity, trusted root and expected peer leaf.
5
6use crate::tls::TlsIdentity;
7use ::openssl::hash::MessageDigest;
8use ::openssl::ssl::{
9    Ssl, SslContext, SslMethod, SslOptions, SslSessionCacheMode, SslVerifyMode, SslVersion,
10};
11use ::openssl::x509::X509Ref;
12use std::{io, net::SocketAddr, pin::Pin, time::Duration};
13use tokio::{net::TcpStream, time::timeout};
14use tokio_openssl::SslStream;
15/// A mutually authenticated simulator TLS connection.
16pub type SecureStream = SslStream<TcpStream>;
17
18/// A mutual TLS endpoint with a dedicated trust anchor and an exact peer leaf pin.
19pub struct TlsEndpoint {
20    context: SslContext,
21    pin: [u8; 32],
22}
23
24impl TlsEndpoint {
25    /// Configure mutual TLS with a provisioned local signing identity, a dedicated
26    /// trust anchor and an exact peer leaf pin. The handshake verifies the chain
27    /// and certificate purpose before accepting the pinned peer.
28    pub fn from_identity(
29        identity: TlsIdentity,
30        trust_anchor: &X509Ref,
31        peer_leaf: &X509Ref,
32    ) -> io::Result<Self> {
33        let pin = leaf_fingerprint(peer_leaf)?;
34        let mut context = identity.into_context_builder(SslMethod::tls())?;
35        context.set_min_proto_version(Some(SslVersion::TLS1_2))?;
36        context.set_max_proto_version(Some(SslVersion::TLS1_2))?;
37        context.set_groups_list("brainpoolP256r1")?;
38        context.set_cipher_list("ECDHE-ECDSA-AES128-GCM-SHA256")?;
39        context.set_options(
40            SslOptions::NO_RENEGOTIATION | SslOptions::NO_TICKET | SslOptions::NO_COMPRESSION,
41        );
42        context.set_session_cache_mode(SslSessionCacheMode::OFF);
43        context.cert_store_mut().add_cert(trust_anchor.to_owned())?;
44        context.set_verify_depth(2);
45        context.set_verify_callback(
46            SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT,
47            move |valid, chain| {
48                valid
49                    && (chain.error_depth() != 0
50                        || chain.current_cert().is_some_and(|leaf| {
51                            leaf_fingerprint(leaf).is_ok_and(|seen| seen == pin)
52                        }))
53            },
54        );
55        Ok(Self {
56            context: context.build(),
57            pin,
58        })
59    }
60
61    /// The SHA-256 certificate fingerprint captured by this endpoint's verification callback.
62    pub fn peer_fingerprint(&self) -> [u8; 32] {
63        self.pin
64    }
65
66    /// Dials the literal loopback address and sends SNI within one setup budget.
67    pub async fn connect(
68        &self,
69        address: SocketAddr,
70        sni: &str,
71        budget: Duration,
72    ) -> io::Result<SslStream<TcpStream>> {
73        check_loopback(address)?;
74        timeout(budget, async {
75            self.connect_socket(TcpStream::connect(address).await?, sni, budget)
76                .await
77        })
78        .await?
79    }
80
81    /// Start pinned client TLS on an already connected simulator socket.
82    pub async fn connect_socket(
83        &self,
84        tcp: TcpStream,
85        sni: &str,
86        budget: Duration,
87    ) -> io::Result<SecureStream> {
88        check_loopback(tcp.peer_addr()?)?;
89        check_server_name(sni)?;
90        let mut ssl = Ssl::new(&self.context)?;
91        ssl.set_hostname(sni)?;
92        let mut tls = SslStream::new(ssl, tcp)?;
93        timeout(budget, Pin::new(&mut tls).connect())
94            .await?
95            .map_err(io::Error::other)?;
96        Ok(tls)
97    }
98
99    /// Accepts a mutually authenticated TLS session on an existing loopback socket.
100    pub async fn accept(
101        &self,
102        tcp: TcpStream,
103        budget: Duration,
104    ) -> io::Result<SslStream<TcpStream>> {
105        check_loopback(tcp.local_addr()?)?;
106        check_loopback(tcp.peer_addr()?)?;
107        let mut tls = SslStream::new(Ssl::new(&self.context)?, tcp)?;
108        timeout(budget, Pin::new(&mut tls).accept())
109            .await?
110            .map_err(io::Error::other)?;
111        Ok(tls)
112    }
113}
114
115/// Compute the leaf pin used when commissioning a loopback TLS endpoint.
116pub fn leaf_fingerprint(leaf: &X509Ref) -> io::Result<[u8; 32]> {
117    let digest = leaf.digest(MessageDigest::sha256())?;
118    digest.as_ref().try_into().map_err(io::Error::other)
119}
120
121/// Validate a configured simulator address before any connection or bind.
122pub fn check_loopback(address: SocketAddr) -> io::Result<()> {
123    if address.ip().is_loopback() {
124        Ok(())
125    } else {
126        Err(io::Error::new(
127            io::ErrorKind::InvalidInput,
128            "the simulator requires a loopback address",
129        ))
130    }
131}
132
133/// Validate a DNS name used for TLS SNI or a simulator route.
134pub fn check_server_name(name: &str) -> io::Result<()> {
135    let valid = name.len() <= 253
136        && name.parse::<std::net::IpAddr>().is_err()
137        && name.split('.').all(|label| {
138            !label.is_empty()
139                && label.len() <= 63
140                && !label.starts_with('-')
141                && !label.ends_with('-')
142                && label
143                    .bytes()
144                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
145        });
146    if valid {
147        Ok(())
148    } else {
149        Err(io::Error::new(
150            io::ErrorKind::InvalidInput,
151            "expected a DNS name for TLS SNI",
152        ))
153    }
154}