Skip to main content

coqui_peer_tls/
pairing.rs

1//! Pairing over TLS: the `coqui_peer::pair` exchange on a connection of its own, under a pairing
2//! ALPN, bound to the connection by its exporter; and key rotation over an authenticated one.
3
4use alloc::sync::Arc;
5use core::net::SocketAddr;
6use core::time::Duration;
7use std::io::{self, Read, Write};
8use std::time::{Instant, SystemTime};
9
10use coqui_peer::pair::{
11    Channel, Mode, Paired, Pairing, PairingDesk, PairingError, PairingJoiner, PairingResponder,
12    Rotation, Shown,
13};
14use coqui_peer::{
15    KeyMaterial, PeerId, Random, ReadTimeout, TrustStore, WriteTimeout, read_frame, write_frame,
16};
17use rustls::pki_types::ServerName;
18use rustls::{ClientConfig, ClientConnection, ServerConfig, ServerConnection, StreamOwned};
19
20use crate::certificate::key_for;
21use crate::config::{ClientAuth, ClientBuilder, ServerBuilder, crypto_provider, failed};
22use crate::error::PeerError;
23use crate::identity::{Identity, PeerIdentity};
24use crate::policy::{CertificateType, Policy};
25use crate::settings::Alpn;
26use crate::stream::{PeerAddr, SERVER_NAME, accept_from_as, dial_named};
27use crate::trust::{Pins, Trust};
28use coqui_builder::Describe;
29
30/// The default ALPN of a pairing connection.
31pub const PAIR_ALPN: &[u8] = b"coqui-pair/1";
32
33/// The label of the TLS exporter (RFC 8446 section 7.5, RFC 5705) that binds a pairing
34/// exchange to its connection; 32 bytes with an empty context.
35pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-coqui-pair";
36
37/// The TLS side of pairing: the device's own [`Policy`] and the ALPN that marks a pairing
38/// connection. Nothing here sets a TLS version or suite; the policy does.
39///
40/// Plain data: start from [`Default`] and assign the fields. The type is [`Describe`], the one a
41/// file or a form fills through a `coqui_builder::Partial` (`alpn` as text, `timeout` as a
42/// duration such as `30` or `15m`, or `never`), and `#[non_exhaustive]`.
43#[derive(Debug, Clone, PartialEq, Eq, Describe)]
44#[map(deny_unknown_fields)]
45#[non_exhaustive]
46pub struct PairConfig {
47    /// The policy both pairing configurations are built with. Default [`Policy::default`].
48    #[map(default)]
49    pub policy: Policy,
50    /// The pairing ALPN; only a connection that negotiated it carries a pairing exchange, and
51    /// only the configurations built here admit a key-proven certificate nobody trusts yet.
52    /// Default [`PAIR_ALPN`].
53    #[map(default = pair_alpn())]
54    pub alpn: Alpn,
55    /// How long one side's whole exchange may take, the TLS handshake included: the joiner's
56    /// dial and finish together, the responder's accept. `None` (the text `never`) waits
57    /// forever. Default 15 minutes, longer than the default `device_ttl` an operator has to
58    /// approve.
59    #[map(default = Some(DEFAULT_TIMEOUT), none = "never")]
60    pub timeout: Option<Duration>,
61}
62
63const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15 * 60);
64
65fn pair_alpn() -> Alpn {
66    Alpn::try_from(PAIR_ALPN).expect("the pairing ALPN is text of 1 to 255 bytes")
67}
68
69impl Default for PairConfig {
70    fn default() -> Self {
71        Self {
72            policy: Policy::default(),
73            alpn: pair_alpn(),
74            timeout: Some(DEFAULT_TIMEOUT),
75        }
76    }
77}
78
79/// How a joiner checks the responder's certificate on the pairing connection.
80#[derive(Debug, Clone)]
81#[non_exhaustive]
82pub enum ResponderTrust {
83    /// Any certificate whose key the responder proves. Enough for a PIN, which authenticates
84    /// the responder; the device flow refuses it unless [`Pairing::allow_unverified`].
85    Unverified,
86    /// Verified by `trust` (pins, a store, or roots for `name`) before anything is sent.
87    Verified {
88        /// The trust.
89        trust: Box<Trust>,
90        /// The server name to send: the host dialled, which roots check; `None` sends
91        /// [`SERVER_NAME`], which pins ignore.
92        name: Option<ServerName<'static>>,
93    },
94}
95
96impl ResponderTrust {
97    /// Verified by pinning `id`.
98    pub fn pinned(id: PeerId) -> Self {
99        Self::Verified {
100            trust: Box::new(Trust::Pinned(Pins::fixed([id]))),
101            name: None,
102        }
103    }
104
105    fn verifies(&self) -> bool {
106        match self {
107            Self::Unverified => false,
108            Self::Verified { trust, .. } => !matches!(**trust, Trust::AnyWithKeyProof),
109        }
110    }
111}
112
113/// A [`Random`] drawing from the TLS provider's secure random source, for a
114/// [`PairingDesk`] and invitations.
115pub fn random() -> Random {
116    let provider = crypto_provider();
117    Random::from_fn(move |out| {
118        provider
119            .secure_random
120            .fill(out)
121            .map_err(|_| coqui_peer::Error::Random)
122    })
123}
124
125/// The server configuration of a pairing connection: `identity`, any client certificate whose
126/// key is proven, `config`'s ALPN and policy. A server on one port serves it to clients that
127/// offer the pairing ALPN (`asynch::accept_with`) and its own configuration to the rest.
128///
129/// # Errors
130///
131/// As [`ServerBuilder::build`].
132pub fn pair_server_config(
133    identity: &Identity,
134    config: &PairConfig,
135) -> Result<ServerConfig, PeerError> {
136    Ok(ServerBuilder::new()
137        .identity(identity)
138        .client_auth(ClientAuth::Required(Trust::AnyWithKeyProof))
139        .alpn([config.alpn.clone()])
140        .policy(config.policy.clone())
141        .build()
142        .map_err(failed)?
143        .config)
144}
145
146/// The client configuration of a pairing connection for `pairing`: an invitation pins the
147/// inviter; otherwise `responder` decides.
148///
149/// # Errors
150///
151/// [`PeerError::Pairing`] with [`PairingError::Unverified`] for the device flow under
152/// [`ResponderTrust::Unverified`] unless the pairing allows it; as [`ClientBuilder::build`].
153pub fn pair_client_config(
154    identity: &Identity,
155    pairing: &Pairing,
156    responder: &ResponderTrust,
157    config: &PairConfig,
158) -> Result<(ClientConfig, ServerName<'static>), PeerError> {
159    let chosen = match pairing.inviter() {
160        Some(inviter) => ResponderTrust::pinned(inviter),
161        None => responder.clone(),
162    };
163    if pairing.mode() == Mode::Device && !chosen.verifies() && !pairing.allows_unverified() {
164        return Err(PeerError::Pairing(PairingError::Unverified));
165    }
166    let (trust, name) = match chosen {
167        ResponderTrust::Unverified => (Trust::AnyWithKeyProof, None),
168        ResponderTrust::Verified { trust, name } => (*trust, name),
169    };
170    let name = match name {
171        Some(name) => name,
172        None => ServerName::try_from(SERVER_NAME).map_err(|_| PeerError::Tls)?,
173    };
174    let built = ClientBuilder::new()
175        .server(trust)
176        .identity(identity)
177        .alpn([config.alpn.clone()])
178        .policy(config.policy.clone())
179        .build()
180        .map_err(failed)?;
181    Ok((built.config, name))
182}
183
184/// Whether the joiner's check of the responder verifies who it is, not only that it holds its
185/// key: an invitation pins the inviter, and `Verified` trust other than `AnyWithKeyProof`.
186pub(crate) fn responder_verified(pairing: &Pairing, responder: &ResponderTrust) -> bool {
187    pairing.inviter().is_some() || responder.verifies()
188}
189
190/// The channel a finished pairing connection gives the exchange: both certificates (proven by
191/// the handshake), whether the remote one was also verified, and the exporter.
192pub(crate) fn channel(
193    connection: &rustls::CommonState,
194    exporter: [u8; 32],
195    local: &Identity,
196    peer: &PeerIdentity,
197    verified: bool,
198    alpn: &[u8],
199    kind: CertificateType,
200) -> Result<Channel, PeerError> {
201    if connection.alpn_protocol() != Some(alpn) {
202        return Err(PeerError::Tls);
203    }
204    let own = match kind {
205        CertificateType::X509 => local.certificate_der(),
206        CertificateType::RawPublicKey => local.public_key_der(),
207    };
208    Ok(Channel {
209        local: key_for(kind, own)?,
210        remote: Some(key_for(kind, &peer.certificate)?),
211        verified,
212        binding: Some(exporter.to_vec()),
213    })
214}
215
216/// The instant `timeout` from now; `None` when there is no timeout or it is too far to represent,
217/// which waits forever.
218pub(crate) fn ends(timeout: Option<Duration>) -> Option<Instant> {
219    timeout.and_then(|timeout| Instant::now().checked_add(timeout))
220}
221
222/// The time left until `until`, at least a millisecond (a zero read timeout is an error).
223pub(crate) fn left(until: Option<Instant>) -> Option<Duration> {
224    until.map(|until| {
225        until
226            .saturating_duration_since(Instant::now())
227            .max(Duration::from_millis(1))
228    })
229}
230
231/// The sooner of `left` and a responder's own time left on the desk's clock.
232pub(crate) fn sooner(left: Option<Duration>, responder: Option<Duration>) -> Option<Duration> {
233    let responder = responder.map(|time| time.max(Duration::from_millis(1)));
234    match (left, responder) {
235        (Some(left), Some(responder)) => Some(left.min(responder)),
236        (left, responder) => left.or(responder),
237    }
238}
239
240pub(crate) fn timed_out(error: &io::Error) -> bool {
241    matches!(
242        error.kind(),
243        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
244    )
245}
246
247/// A joiner's pairing connection, past the point where it has something to show (or done).
248#[derive(Debug)]
249pub struct PairDial<S: Read + Write + ReadTimeout + WriteTimeout> {
250    tls: StreamOwned<ClientConnection, S>,
251    joiner: PairingJoiner,
252    until: Option<Instant>,
253}
254
255impl<S: Read + Write + ReadTimeout + WriteTimeout> PairDial<S> {
256    /// What to show a person now: this joiner's PIN with its slot, or the device-flow user
257    /// code. `None` when the mode shows nothing.
258    pub fn shown(&self) -> Option<&Shown> {
259        self.joiner.shown()
260    }
261
262    /// Runs the exchange to its end (for a shown code, until the operator acts at the
263    /// responder), accepts the responder's certificate in `store`, and closes the connection.
264    /// It waits at most what is left of [`PairConfig::timeout`] from [`pair_dial`].
265    ///
266    /// # Errors
267    ///
268    /// [`PeerError::Pairing`] when either side refused; [`PeerError::Io`] when the connection
269    /// fails or the timeout passes (`TimedOut`); [`PeerError::Certificate`] or
270    /// [`PeerError::Io`] when the store cannot write.
271    pub fn finish(mut self, store: &TrustStore) -> Result<Paired, PeerError> {
272        join_until(&mut self.tls, &mut self.joiner, self.until, |_| false)?;
273        let paired = self.joiner.finish()?;
274        match store.accept_key(&paired.peer) {
275            Ok(_) | Err(coqui_peer::Error::AlreadyAccepted) => {}
276            Err(error) => return Err(error.into()),
277        }
278        self.tls.conn.send_close_notify();
279        let _ = self.tls.flush();
280        Ok(paired)
281    }
282}
283
284/// Moves joiner messages until `stop` holds, the joiner completes, it fails, or `until` passes.
285fn join_until<S: Read + Write + ReadTimeout + WriteTimeout>(
286    tls: &mut StreamOwned<ClientConnection, S>,
287    joiner: &mut PairingJoiner,
288    until: Option<Instant>,
289    stop: impl Fn(&PairingJoiner) -> bool,
290) -> Result<(), PeerError> {
291    loop {
292        tls.sock
293            .set_write_timeout(left(until))
294            .map_err(PeerError::Io)?;
295        while let Some(message) = joiner.transmit() {
296            write_frame(tls, &message).map_err(PeerError::Io)?;
297        }
298        if joiner.is_complete() || stop(joiner) {
299            return Ok(());
300        }
301        tls.sock
302            .set_read_timeout(left(until))
303            .map_err(PeerError::Io)?;
304        let message = read_frame(tls).map_err(PeerError::Io)?;
305        if let Err(error) = joiner.receive(&message) {
306            // The joiner may have queued a refusal for the responder.
307            while let Some(message) = joiner.transmit() {
308                let _ = write_frame(tls, &message);
309            }
310            return Err(error.into());
311        }
312    }
313}
314
315/// Dials a pairing connection over `stream` as `identity` and runs `pairing` until there is
316/// something to [`show`](PairDial::shown), or to its end; [`PairDial::finish`] completes it.
317///
318/// The connection uses `config`'s policy and ALPN and is bound to the exchange by its exporter.
319/// An invitation pins the inviter; a PIN pairing may leave the responder
320/// [`Unverified`](ResponderTrust::Unverified) because the PIN authenticates it; the device flow
321/// needs a [`Verified`](ResponderTrust::Verified) responder unless the pairing allows otherwise.
322/// The handshake, this call and [`PairDial::finish`] together wait at most
323/// [`PairConfig::timeout`].
324///
325/// # Errors
326///
327/// [`PeerError::Pairing`]; [`PeerError::Io`] when the handshake or connection fails or the
328/// timeout passes (a pinned inviter that is someone else is refused here, with
329/// [`PeerError::refusal`]); [`PeerError::Tls`] when the server did not negotiate the pairing
330/// ALPN.
331pub fn pair_dial<S: Read + Write + ReadTimeout + WriteTimeout>(
332    stream: S,
333    identity: &Identity,
334    pairing: Pairing,
335    responder: &ResponderTrust,
336    config: &PairConfig,
337) -> Result<PairDial<S>, PeerError> {
338    let until = ends(config.timeout);
339    let (client, name) = pair_client_config(identity, &pairing, responder, config)?;
340    let verified = responder_verified(&pairing, responder);
341    stream
342        .set_read_timeout(left(until))
343        .and_then(|()| stream.set_write_timeout(left(until)))
344        .map_err(PeerError::Io)?;
345    let (tls, peer) = dial_named(Arc::new(client), name, stream)?;
346    let exporter = tls
347        .conn
348        .export_keying_material([0u8; 32], EXPORTER_LABEL, Some(&[]))
349        .map_err(|_| PeerError::Tls)?;
350    let channel = channel(
351        &tls.conn,
352        exporter,
353        identity,
354        &peer,
355        verified,
356        config.alpn.as_bytes(),
357        config.policy.certificate,
358    )?;
359    let mut dial = PairDial {
360        tls,
361        joiner: pairing.join(channel)?,
362        until,
363    };
364    join_until(&mut dial.tls, &mut dial.joiner, until, |joiner| {
365        joiner.shown().is_some()
366    })?;
367    Ok(dial)
368}
369
370/// Accepts a pairing connection over `stream` as `identity` and runs the responder's side to
371/// its end: redeeming an invitation from `store`, taking PINs and decisions from `desk` (this
372/// call blocks while the operator decides), and accepting the joiner's certificate in `store`.
373/// The address of `stream` is the source the desk throttles by.
374///
375/// Every read waits at most the sooner of what is left of [`PairConfig::timeout`] and the
376/// responder's own deadline (`pin_ttl` or `device_ttl` from the joiner's first message); past
377/// that deadline the joiner is told `Expired`.
378///
379/// # Errors
380///
381/// [`PeerError::Pairing`] when either side refused or the deadline passed; [`PeerError::Io`]
382/// when the handshake or the connection fails or the timeout passes (`TimedOut`);
383/// [`PeerError::Tls`] when the client did not negotiate the pairing ALPN.
384pub fn pair_accept<S: Read + Write + PeerAddr + ReadTimeout + WriteTimeout>(
385    stream: S,
386    identity: &Identity,
387    store: &TrustStore,
388    desk: &PairingDesk,
389    config: &PairConfig,
390) -> Result<Paired, PeerError> {
391    let (source, local) = (stream.peer_addr(), stream.local_addr());
392    pair_accept_as(stream, (source, local), identity, store, desk, config)
393}
394
395fn pair_accept_as<S: Read + Write + ReadTimeout + WriteTimeout>(
396    stream: S,
397    (source, local): (Option<SocketAddr>, Option<SocketAddr>),
398    identity: &Identity,
399    store: &TrustStore,
400    desk: &PairingDesk,
401    config: &PairConfig,
402) -> Result<Paired, PeerError> {
403    let until = ends(config.timeout);
404    let server = Arc::new(pair_server_config(identity, config)?);
405    stream
406        .set_read_timeout(left(until))
407        .and_then(|()| stream.set_write_timeout(left(until)))
408        .map_err(PeerError::Io)?;
409    let (mut tls, peer) = accept_from_as(server, stream, source, local)?;
410    let exporter = tls
411        .conn
412        .export_keying_material([0u8; 32], EXPORTER_LABEL, Some(&[]))
413        .map_err(|_| PeerError::Tls)?;
414    let channel = channel(
415        &tls.conn,
416        exporter,
417        identity,
418        &peer,
419        false,
420        config.alpn.as_bytes(),
421        config.policy.certificate,
422    )?;
423    let mut responder = PairingResponder::new(channel, store, desk, source);
424    let result = respond(&mut tls, &mut responder, desk, until);
425    tls.conn.send_close_notify();
426    let _ = tls.flush();
427    result?;
428    Ok(responder.finish()?)
429}
430
431fn respond<S: Read + Write + ReadTimeout + WriteTimeout>(
432    tls: &mut StreamOwned<ServerConnection, S>,
433    responder: &mut PairingResponder,
434    desk: &PairingDesk,
435    until: Option<Instant>,
436) -> Result<(), PeerError> {
437    loop {
438        tls.sock
439            .set_write_timeout(left(until))
440            .map_err(PeerError::Io)?;
441        while let Some(message) = responder.transmit() {
442            write_frame(tls, &message).map_err(PeerError::Io)?;
443        }
444        if responder.is_complete() {
445            return Ok(());
446        }
447        let step = match responder.awaiting() {
448            Some(ticket) => responder.resume(desk.wait(ticket)),
449            None => {
450                let wait = sooner(left(until), responder.time_left());
451                tls.sock.set_read_timeout(wait).map_err(PeerError::Io)?;
452                match read_frame(tls) {
453                    Ok(message) => responder.receive(&message),
454                    // Past the responder's deadline the joiner is told; past the transport's
455                    // own timeout the connection just ends.
456                    Err(error) if timed_out(&error) => match responder.check_deadline() {
457                        Err(expired) => Err(expired),
458                        Ok(()) => return Err(PeerError::Io(error)),
459                    },
460                    Err(error) => return Err(PeerError::Io(error)),
461                }
462            }
463        };
464        if let Err(error) = step {
465            while let Some(message) = responder.transmit() {
466                let _ = write_frame(tls, &message);
467            }
468            return Err(error.into());
469        }
470    }
471}
472
473/// Announces `successor` as the next identity of this side, over a connection the current
474/// identity authenticated: one framed [`Rotation`] message. What follows on the connection is
475/// the caller's protocol.
476///
477/// # Errors
478///
479/// [`PeerError::Certificate`] for an unusable certificate, [`PeerError::Io`].
480pub fn announce(stream: &mut impl Write, successor: &Identity) -> Result<(), PeerError> {
481    announce_as(stream, successor, CertificateType::X509)
482}
483
484/// [`announce`] for a connection whose peers authenticate as `kind`: with
485/// [`RawPublicKey`](CertificateType::RawPublicKey) the successor is announced by its raw public
486/// key, which is what its next handshake presents.
487///
488/// # Errors
489///
490/// As [`announce`].
491pub fn announce_as(
492    stream: &mut impl Write,
493    successor: &Identity,
494    kind: CertificateType,
495) -> Result<(), PeerError> {
496    let der = match kind {
497        CertificateType::X509 => successor.certificate_der(),
498        CertificateType::RawPublicKey => successor.public_key_der(),
499    };
500    let key = key_for(kind, der)?;
501    write_frame(stream, &Rotation::announce(&key)).map_err(PeerError::Io)
502}
503
504/// Reads an [`announce`]ment from `sender` (the verified peer of this connection) and records
505/// it in `store` as the pending successor of `sender`'s certificate. Returns the successor's id.
506/// The next handshake that proves it promotes it, unless the store's rotation options require
507/// approval.
508///
509/// # Errors
510///
511/// [`PeerError::Pairing`] with [`PairingError::Protocol`] for anything but an announcement of a
512/// certificate; [`PeerError::NotWaiting`]-style store errors as [`PeerError`] (an announcement
513/// by a peer that is not accepted, or retiring, is refused); [`PeerError::Io`].
514pub fn receive_announcement(
515    stream: &mut impl Read,
516    store: &TrustStore,
517    sender: &PeerIdentity,
518) -> Result<PeerId, PeerError> {
519    let message = read_frame(stream).map_err(PeerError::Io)?;
520    record_announcement(&message, store, sender)
521}
522
523pub(crate) fn record_announcement(
524    message: &[u8],
525    store: &TrustStore,
526    sender: &PeerIdentity,
527) -> Result<PeerId, PeerError> {
528    let key: KeyMaterial = Rotation::parse(message)?;
529    if key.method != crate::METHOD {
530        return Err(PeerError::Pairing(PairingError::Protocol));
531    }
532    store.announce_successor(&sender.fingerprint, &key)?;
533    Ok(key.id())
534}
535
536impl Identity {
537    /// Whether this identity's certificate ends within `margin` from now: time to make a
538    /// successor and [`announce`] it. An unreadable validity is due.
539    pub fn renew_before(&self, margin: Duration) -> bool {
540        self.renew_before_at(margin, SystemTime::now())
541    }
542
543    /// [`renew_before`](Identity::renew_before) at `now`.
544    pub fn renew_before_at(&self, margin: Duration, now: SystemTime) -> bool {
545        let Ok((_, not_after)) = crate::x509::validity(self.certificate_der()) else {
546            return true;
547        };
548        let now = now
549            .duration_since(SystemTime::UNIX_EPOCH)
550            .map_or(0, |elapsed| elapsed.as_secs());
551        let deadline = i128::from(now) + i128::from(margin.as_secs());
552        deadline >= i128::from(not_after)
553    }
554}