Skip to main content

bitwarden_ipc/crypto_provider/noise/
crypto_provider.rs

1use std::time::Duration;
2
3use bitwarden_threading::time::timeout;
4use serde::{Deserialize, Serialize};
5use tracing::{debug, error, info, warn};
6
7use crate::{
8    crypto_provider::noise::{
9        NOISE_MAX_MESSAGE_LEN, NOISE_TAG_LEN,
10        handshake::{
11            CipherSuite, HandshakeFinishMessage, HandshakeInitiator, HandshakeResponder,
12            HandshakeStartMessage,
13        },
14        transport_state::{PersistentTransportState, TransportFrame},
15    },
16    error::{ErrorKind, IpcErrorKind},
17    message::{IncomingMessage, OutgoingMessage},
18    timeline::{self, Entry, Track},
19    traits::{
20        CommunicationBackend, CommunicationBackendReceiver, CryptoProvider, SessionRepository,
21    },
22};
23
24/// A `CryptoProvider` that encrypts IPC traffic using the Noise protocol.
25#[derive(Default)]
26pub struct NoiseCryptoProvider {
27    /// Serializes access to the persisted transport state, so that two concurrent sends cannot
28    /// read the same copy and reuse a nonce.
29    ///
30    /// Held per provider, and so per [`IpcClientImpl`](crate::IpcClientImpl), rather than per
31    /// process: the state it protects belongs to one client's session repository, and a
32    /// process-wide lock would let one client's handshake — which can wait
33    /// [`HANDSHAKE_TIMEOUT_SECS`] for a reply — stall every other client's traffic.
34    crypto_state_guard: tokio::sync::Mutex<()>,
35}
36
37impl NoiseCryptoProvider {
38    /// Creates a provider with no sessions established.
39    pub fn new() -> Self {
40        Self::default()
41    }
42}
43
44#[derive(Debug)]
45pub enum NoiseCryptoProviderError {
46    /// A protocol error (missing message, malformed message)
47    HandshakeProtocol,
48    /// A timeout waiting for a message
49    Timeout,
50    /// The destination could not be reached (the underlying transport is not connected).
51    TransportUnreachable,
52    /// Could not send via the underlying transport. `kind` is the underlying backend error's
53    /// [`IpcErrorKind`] classification.
54    TransportSend { kind: ErrorKind },
55    /// Could not receive via the underlying transport. `kind` is the underlying backend error's
56    /// [`IpcErrorKind`] classification.
57    TransportReceive { kind: ErrorKind },
58    /// A cryptographic error. In most cases, such messages are just dropped.
59    DecryptionFailure,
60}
61
62impl IpcErrorKind for NoiseCryptoProviderError {
63    fn kind(&self) -> ErrorKind {
64        match self {
65            // A bad/missing handshake frame from one peer does not affect the shared client; the
66            // peer can retry the handshake.
67            NoiseCryptoProviderError::HandshakeProtocol => ErrorKind::Other,
68            // The handshake is retryable on a subsequent send.
69            NoiseCryptoProviderError::Timeout => ErrorKind::Other,
70            // A decryption failure only affects the offending message, which is dropped.
71            NoiseCryptoProviderError::DecryptionFailure => ErrorKind::Other,
72            // An unreachable destination; the message simply could not be delivered.
73            NoiseCryptoProviderError::TransportUnreachable => ErrorKind::Unreachable,
74            // Defer to the underlying backend's classification, captured at construction.
75            NoiseCryptoProviderError::TransportSend { kind }
76            | NoiseCryptoProviderError::TransportReceive { kind } => *kind,
77        }
78    }
79}
80
81/// Classify a transport send failure: an unreachable destination becomes the dedicated
82/// [`NoiseCryptoProviderError::TransportUnreachable`], while every other failure preserves the
83/// underlying backend's fatal/recoverable classification.
84fn transport_send_error<E: IpcErrorKind>(e: E) -> NoiseCryptoProviderError {
85    match e.kind() {
86        ErrorKind::Unreachable => NoiseCryptoProviderError::TransportUnreachable,
87        kind => NoiseCryptoProviderError::TransportSend { kind },
88    }
89}
90
91impl NoiseCryptoProvider {
92    async fn perform_handshake<Com, Ses>(
93        communication: &Com,
94        sessions: &Ses,
95        destination: crate::endpoint::Endpoint,
96    ) -> Result<(), NoiseCryptoProviderError>
97    where
98        Com: CommunicationBackend,
99        Ses: SessionRepository<NoiseCryptoProviderState>,
100    {
101        debug!("Starting noise handshake with {:?}", destination);
102        let _span = timeline::span(Track::Handshakes, timeline::Duration::Actual, || {
103            handshake_entry("Initiator", &destination)
104        });
105
106        let mut initiator = HandshakeInitiator::new(&CipherSuite::default());
107        let message = initiator
108            .write_start_message()
109            .expect("Handshake start message should be buildable");
110        let receiver = communication.subscribe().await;
111
112        let handshake_frame = Frame::HandshakeStart(message);
113        communication
114            .send(OutgoingMessage {
115                payload: handshake_frame.to_cbor(),
116                destination: destination.clone(),
117                topic: None,
118            })
119            .await
120            .map_err(transport_send_error)?;
121
122        // Wait for the handshake response (with timeout)
123        timeout(Duration::from_secs(HANDSHAKE_TIMEOUT_SECS), async {
124            loop {
125                let incoming = receiver
126                    .receive()
127                    .await
128                    .map_err(|e| NoiseCryptoProviderError::TransportReceive { kind: e.kind() })?;
129
130                // For concurrent handshakes, ignore messages
131                if incoming.source.to_endpoint() != destination {
132                    continue;
133                }
134
135                // Malformed messages will cancel the handshake
136                let Ok(response_frame) = Frame::from_cbor(&incoming.payload) else {
137                    return Err(NoiseCryptoProviderError::HandshakeProtocol);
138                };
139
140                // Only accept handshake finish messages until the handshake is complete
141                if let Frame::HandshakeFinish(handshake_finish) = response_frame {
142                    if initiator.read_response_message(&handshake_finish).is_err() {
143                        error!("Failed to read handshake response message");
144                        return Err(NoiseCryptoProviderError::HandshakeProtocol);
145                    }
146                    break;
147                }
148            }
149            Ok(())
150        })
151        .await
152        .map_err(|_| {
153            debug!(
154                "Noise handshake with {:?} timed out after {} seconds",
155                destination, HANDSHAKE_TIMEOUT_SECS
156            );
157            NoiseCryptoProviderError::Timeout
158            // Both the timeout error, and errors from within the handshake loop are propagated
159            // here, hence the double question mark.
160        })??;
161
162        let crypto_state = NoiseCryptoProviderState {
163            state: (&mut initiator).into(),
164        };
165        sessions
166            .save(destination.clone(), crypto_state)
167            .await
168            .expect("Save session should not fail");
169
170        info!(
171            "Noise handshake with {:?} completed, session established",
172            destination
173        );
174
175        Ok(())
176    }
177}
178
179/// Timeline entry for a handshake, e.g. "Noise handshake" as "Initiator" with "DesktopMain".
180fn handshake_entry(role: &str, peer: &crate::endpoint::Endpoint) -> Entry {
181    Entry {
182        name: "Noise handshake".to_owned(),
183        properties: vec![("Role", role.to_owned()), ("Peer", format!("{peer:?}"))],
184    }
185}
186
187/// Re-handshake interval in seconds. Sessions older than this will automatically
188/// re-key on the next send operation.
189const REHANDSHAKE_INTERVAL_SECS: u64 = 300;
190
191/// Timeout for waiting for a handshake response from the remote peer.
192const HANDSHAKE_TIMEOUT_SECS: u64 = 2;
193
194/// Session state for the Noise crypto provider.
195#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct NoiseCryptoProviderState {
197    state: PersistentTransportState,
198}
199
200impl<Com, Ses> CryptoProvider<Com, Ses> for NoiseCryptoProvider
201where
202    Com: CommunicationBackend,
203    Ses: SessionRepository<NoiseCryptoProviderState>,
204{
205    type Session = NoiseCryptoProviderState;
206    type SendError = NoiseCryptoProviderError;
207    type ReceiveError = NoiseCryptoProviderError;
208
209    fn max_payload_len(&self) -> usize {
210        NOISE_MAX_MESSAGE_LEN - NOISE_TAG_LEN
211    }
212
213    async fn send(
214        &self,
215        communication: &Com,
216        sessions: &Ses,
217        message: OutgoingMessage,
218    ) -> Result<(), Self::SendError> {
219        // Send operations *MUST* be serialized, otherwise nonce re-use may happen since
220        // concurrent sends may acquire the same copy of the transport state before nonce
221        // updating.
222        let _crypto_state_guard = self.crypto_state_guard.lock().await;
223
224        let destination = message.destination.clone();
225
226        let crypto_state = sessions
227            .get(destination.clone())
228            .await
229            .expect("Get session should not fail");
230
231        let mut should_handshake = crypto_state.is_none();
232        if let Some(state) = crypto_state.as_ref()
233            && state.state.should_rehandshake(REHANDSHAKE_INTERVAL_SECS)
234        {
235            info!(
236                "Noise session with {:?} is older than {}s, re-handshaking",
237                destination, REHANDSHAKE_INTERVAL_SECS
238            );
239            sessions
240                .remove(destination.clone())
241                .await
242                .expect("Delete session should not fail");
243            should_handshake = true;
244        }
245
246        if should_handshake {
247            if crypto_state.is_none() {
248                debug!(
249                    "Noise handshake with {:?} initiated for new session establishment",
250                    destination
251                );
252            } else {
253                debug!(
254                    "Noise re-handshake with {:?} due to re-handshake interval",
255                    destination
256                );
257            }
258
259            // Propagate every handshake failure, including an unreachable transport. The
260            // unreachable case surfaces as `NoiseCryptoProviderError::TransportUnreachable`
261            // (non-fatal), which the logging layers intentionally do not log — so it no longer
262            // needs to be swallowed here to avoid spam.
263            Self::perform_handshake(communication, sessions, destination.clone()).await?;
264        }
265
266        let mut crypto_state = sessions
267            .get(destination.clone())
268            .await
269            .expect("Get session should not fail")
270            .expect("Session should exist after handshake");
271
272        // Encrypt and send the payload
273        let transport_frame = crypto_state
274            .state
275            .send(message.payload.into())
276            .map_err(|_| NoiseCryptoProviderError::DecryptionFailure)?;
277        if let Err(e) = communication
278            .send(OutgoingMessage {
279                payload: Frame::TransportFrame(transport_frame).to_cbor(),
280                destination: destination.clone(),
281                topic: message.topic,
282            })
283            .await
284            .map_err(transport_send_error)
285        {
286            match e.kind() {
287                ErrorKind::Fatal => {
288                    error!(
289                        "{:?} fatal error sending message. Clearing cryptographic sessions.",
290                        destination
291                    );
292                    sessions
293                        .remove(destination.clone())
294                        .await
295                        .expect("Delete session should not fail");
296                    return Err(e);
297                }
298                ErrorKind::Unreachable => {
299                    // If a destination goes offline, the cryptographic session is torn down.
300                    // The next time the destination comes back online, a new handshake will be
301                    // performed. If this were not done, then the first message
302                    // would always be dropped by the destination,
303                    // after the destination process-reloads because it would not be decryptable by
304                    // the destination.
305                    info!(
306                        "{:?} is unreachable. Clearing cryptographic sessions.",
307                        destination
308                    );
309                    sessions
310                        .remove(destination.clone())
311                        .await
312                        .expect("Delete session should not fail");
313                    return Err(e);
314                }
315                // Every other recoverable send failure is still surfaced.
316                ErrorKind::Other => {
317                    error!(
318                        "Recoverable error sending message to {:?}: {:?}",
319                        destination, e
320                    );
321                }
322            }
323        }
324
325        sessions
326            .save(destination, crypto_state)
327            .await
328            .expect("Save session should not fail");
329
330        Ok(())
331    }
332
333    async fn receive(
334        &self,
335        receiver: &Com::Receiver,
336        communication: &Com,
337        sessions: &Ses,
338    ) -> Result<IncomingMessage, Self::ReceiveError> {
339        loop {
340            let message = receiver
341                .receive()
342                .await
343                .map_err(|e| NoiseCryptoProviderError::TransportReceive { kind: e.kind() })?;
344
345            // Ensure session exists
346            let source_endpoint: crate::endpoint::Endpoint = message.source.clone().into();
347
348            // Decode outer transport frame from wire
349            let Ok(transport_frame) = Frame::from_cbor(&message.payload) else {
350                warn!("Received malformed cbor message, ignoring");
351                continue;
352            };
353
354            match transport_frame {
355                Frame::HandshakeStart(handshake_start) => {
356                    let _span =
357                        timeline::span(Track::Handshakes, timeline::Duration::Actual, || {
358                            handshake_entry("Responder", &source_endpoint)
359                        });
360                    let mut responder = HandshakeResponder::new(&handshake_start.ciphersuite);
361                    responder
362                        .read_start_message(&handshake_start)
363                        .map_err(|_| NoiseCryptoProviderError::HandshakeProtocol)?;
364                    let response_message = responder
365                        .write_response_message()
366                        .map_err(|_| NoiseCryptoProviderError::HandshakeProtocol)?;
367                    let handshake_frame = Frame::HandshakeFinish(response_message);
368                    communication
369                        .send(OutgoingMessage {
370                            payload: handshake_frame.to_cbor(),
371                            destination: source_endpoint.clone(),
372                            topic: None,
373                        })
374                        .await
375                        .map_err(transport_send_error)?;
376
377                    let crypto_state = NoiseCryptoProviderState {
378                        state: (&mut responder).into(),
379                    };
380                    sessions
381                        .save(source_endpoint, crypto_state)
382                        .await
383                        .expect("Save session should not fail");
384                }
385                Frame::TransportFrame(transport_frame) => {
386                    let _crypto_state_guard = self.crypto_state_guard.lock().await;
387                    let crypto_state = sessions
388                        .get(source_endpoint.clone())
389                        .await
390                        .expect("Get session should not fail");
391                    let Some(mut state) = crypto_state else {
392                        debug!("No session for {:?}, waiting for handshake", message.source);
393                        let frame = Frame::CryptoInvalidated.to_cbor();
394                        communication
395                            .send(OutgoingMessage {
396                                payload: frame,
397                                destination: source_endpoint,
398                                topic: None,
399                            })
400                            .await
401                            .map_err(transport_send_error)?;
402                        continue;
403                    };
404
405                    let payload = state.state.receive(&transport_frame);
406                    let Ok(payload) = payload else {
407                        info!("Failed to decrypt message from {:?}", message.source);
408                        continue;
409                    };
410
411                    sessions
412                        .save(source_endpoint, state)
413                        .await
414                        .expect("Save session should not fail");
415
416                    return Ok(IncomingMessage {
417                        payload: payload.as_ref().to_vec(),
418                        destination: message.destination,
419                        source: message.source,
420                        topic: message.topic,
421                    });
422                }
423                Frame::CryptoInvalidated => {
424                    info!(
425                        "Invalidated session for {:?} due to crypto error, deleting session and waiting for handshake",
426                        message.source
427                    );
428                    sessions
429                        .remove(source_endpoint)
430                        .await
431                        .expect("Delete session should not fail");
432                }
433                _ => continue,
434            }
435        }
436    }
437}
438
439/// The raw frame that is sent via IPC.
440#[derive(Serialize, Deserialize)]
441pub(super) enum Frame {
442    // Handshake Frames
443    HandshakeStart(HandshakeStartMessage),
444    HandshakeFinish(HandshakeFinishMessage),
445    // After the handshake is done, transport frames are used to wrap ciphertexts
446    TransportFrame(TransportFrame),
447    // If crypto is invalidated, this message is sent by the device noticing
448    // the invalidation so that both sides reset the crypto.
449    CryptoInvalidated,
450}
451
452impl Frame {
453    pub(crate) fn to_cbor(&self) -> Vec<u8> {
454        let mut buffer = Vec::new();
455        ciborium::into_writer(self, &mut buffer).expect("Ciborium serialization should not fail");
456        buffer
457    }
458
459    pub(crate) fn from_cbor(buffer: &[u8]) -> Result<Self, ()> {
460        ciborium::from_reader(buffer).map_err(|_| ())
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use std::collections::HashMap;
467
468    use crate::{
469        IpcClientImpl,
470        crypto_provider::noise::crypto_provider::NoiseCryptoProvider,
471        endpoint::Endpoint,
472        ipc_client_trait::IpcClient,
473        message::OutgoingMessage,
474        traits::{InMemorySessionRepository, TestTwoWayCommunicationBackend},
475    };
476
477    #[tokio::test]
478    async fn ping_pong() {
479        let (provider_1, provider_2) = TestTwoWayCommunicationBackend::new();
480
481        let session_map_1 = InMemorySessionRepository::new(HashMap::new());
482        let client_1 = IpcClientImpl::new(NoiseCryptoProvider::new(), provider_1, session_map_1);
483        let _ = client_1.start(None).await;
484        let mut recv_1 = client_1.subscribe(None).await.unwrap();
485
486        let session_map_2 = InMemorySessionRepository::new(HashMap::new());
487        let client_2 = IpcClientImpl::new(NoiseCryptoProvider::new(), provider_2, session_map_2);
488        let _ = client_2.start(None).await;
489        let mut recv_2 = client_2.subscribe(None).await.unwrap();
490
491        let handle_1 = tokio::spawn(async move {
492            let mut val: u8 = 0;
493            for _ in 0..255 {
494                let message = OutgoingMessage {
495                    payload: vec![val],
496                    destination: Endpoint::DesktopMain,
497                    topic: None,
498                };
499                client_1.send(message).await.unwrap();
500                let recv_message = recv_1.receive(None).await.unwrap();
501                val = recv_message.payload[0] + 1;
502            }
503        });
504
505        let handle_2 = tokio::spawn(async move {
506            for _ in 0..255 {
507                let recv_message = recv_2.receive(None).await.unwrap();
508                let val = recv_message.payload[0];
509                if val == 255 {
510                    break;
511                }
512
513                client_2
514                    .send(OutgoingMessage {
515                        payload: vec![val],
516                        destination: Endpoint::DesktopMain,
517                        topic: None,
518                    })
519                    .await
520                    .unwrap();
521            }
522        });
523
524        let _ = tokio::join!(handle_1, handle_2);
525    }
526}