Skip to main content

whisker_dev_protocol/
session.rs

1//! Replay-protected envelopes exchanged after the handshake.
2
3use hmac::{Hmac, Mac};
4use sha2::Sha256;
5
6use crate::{ENVELOPE_OVERHEAD, Error, MAX_CONTROL, MAX_MESSAGE, MAX_PAYLOAD, PROTOCOL_VERSION};
7
8type HmacSha256 = Hmac<Sha256>;
9
10const TAG_LEN: usize = 32;
11const HEADER_LEN: usize = ENVELOPE_OVERHEAD - TAG_LEN;
12
13/// What an envelope's payload contains
14///
15/// The kind is authenticated together with the payload, so a receiver can
16/// route the payload without parsing it first.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[repr(u8)]
19pub enum FrameKind {
20    /// A hot-reload patch: `[u64 BE header length][JSON jump table][library]`
21    ///
22    /// Only the server sends patches.
23    Patch = 1,
24    /// UTF-8 JSON control or metadata, at most [`MAX_CONTROL`] bytes
25    ///
26    /// Covers the client hello, logs, traces, and server control messages.
27    Text = 2,
28}
29
30impl FrameKind {
31    fn from_byte(byte: u8) -> Option<Self> {
32        match byte {
33            1 => Some(Self::Patch),
34            2 => Some(Self::Text),
35            _ => None,
36        }
37    }
38}
39
40/// Which end of the connection a transcript value belongs to
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Role {
43    Client,
44    Server,
45}
46
47impl Role {
48    fn peer(self) -> Self {
49        match self {
50            Self::Client => Self::Server,
51            Self::Server => Self::Client,
52        }
53    }
54
55    fn proof_domain(self) -> &'static [u8] {
56        match self {
57            Self::Client => b"client-proof",
58            Self::Server => b"server-proof",
59        }
60    }
61
62    fn frame_domain(self) -> &'static [u8] {
63        match self {
64            Self::Client => b"client-frame",
65            Self::Server => b"server-frame",
66        }
67    }
68}
69
70fn transcript_mac(
71    secret: &str,
72    domain: &[u8],
73    client_nonce: &[u8; 32],
74    server_nonce: &[u8; 32],
75) -> HmacSha256 {
76    let mut mac =
77        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
78    mac.update(b"whisker-dev-v1\0");
79    mac.update(domain);
80    mac.update(client_nonce);
81    mac.update(server_nonce);
82    mac
83}
84
85pub(crate) fn proof(
86    secret: &str,
87    role: Role,
88    client_nonce: &[u8; 32],
89    server_nonce: &[u8; 32],
90) -> [u8; 32] {
91    transcript_mac(secret, role.proof_domain(), client_nonce, server_nonce)
92        .finalize()
93        .into_bytes()
94        .into()
95}
96
97pub(crate) fn verify_proof(
98    secret: &str,
99    role: Role,
100    client_nonce: &[u8; 32],
101    server_nonce: &[u8; 32],
102    tag: &[u8],
103) -> bool {
104    !secret.is_empty()
105        && transcript_mac(secret, role.proof_domain(), client_nonce, server_nonce)
106            .verify_slice(tag)
107            .is_ok()
108}
109
110/// One authenticated connection's envelope state
111///
112/// A `Session` exists only after a successful handshake
113/// ([`ClientHandshake::finish`](crate::ClientHandshake::finish) or
114/// [`ServerHandshake::finish`](crate::ServerHandshake::finish)). It binds
115/// every envelope to the shared secret, both handshake nonces, and the
116/// sending direction, and keeps one sequence counter per direction.
117///
118/// [`seal`](Self::seal) and [`open`](Self::open) are the only way bytes
119/// enter or leave the authenticated channel; anything [`open`](Self::open)
120/// rejects must not be parsed, and the connection should be closed.
121///
122/// # Example
123///
124/// ```rust
125/// use whisker_dev_protocol::{ClientHandshake, FrameKind, ServerHandshake};
126///
127/// let (client, challenge) = ClientHandshake::start("secret")?;
128/// let (server, server_proof) = ServerHandshake::respond("secret", &challenge)?;
129/// let (mut app, client_proof) = client.finish(&server_proof)?;
130/// let mut host = server.finish(&client_proof)?;
131///
132/// let hello = app.seal(FrameKind::Text, br#"{"kind":"hello","aslr_reference":0}"#)?;
133/// let (kind, payload) = host.open(&hello)?;
134/// assert_eq!(kind, FrameKind::Text);
135/// assert!(payload.starts_with(br#"{"kind":"hello""#));
136///
137/// // A host cannot accept its own envelope back (reflection).
138/// let reflected = host.seal(FrameKind::Text, b"{}")?;
139/// assert!(host.open(&reflected).is_err());
140/// # Ok::<(), whisker_dev_protocol::Error>(())
141/// ```
142pub struct Session {
143    secret: String,
144    client_nonce: [u8; 32],
145    server_nonce: [u8; 32],
146    role: Role,
147    sent: u64,
148    received: u64,
149}
150
151impl Session {
152    pub(crate) fn new(
153        secret: String,
154        client_nonce: [u8; 32],
155        server_nonce: [u8; 32],
156        role: Role,
157    ) -> Self {
158        Self {
159            secret,
160            client_nonce,
161            server_nonce,
162            role,
163            sent: 0,
164            received: 0,
165        }
166    }
167
168    fn frame_mac(&self, sender: Role) -> HmacSha256 {
169        transcript_mac(
170            &self.secret,
171            sender.frame_domain(),
172            &self.client_nonce,
173            &self.server_nonce,
174        )
175    }
176
177    /// Wrap `payload` in an authenticated envelope for the peer
178    ///
179    /// Advances this direction's sequence number. Fails with
180    /// [`Error::FrameTooLarge`] when the payload exceeds [`MAX_PAYLOAD`] (or
181    /// [`MAX_CONTROL`] for [`FrameKind::Text`]), and with
182    /// [`Error::SequenceExhausted`] instead of wrapping the counter.
183    pub fn seal(&mut self, kind: FrameKind, payload: &[u8]) -> Result<Vec<u8>, Error> {
184        if payload.len() > MAX_PAYLOAD || (kind == FrameKind::Text && payload.len() > MAX_CONTROL) {
185            return Err(Error::FrameTooLarge);
186        }
187        let next = self.sent.checked_add(1).ok_or(Error::SequenceExhausted)?;
188        let mut frame = Vec::with_capacity(payload.len() + ENVELOPE_OVERHEAD);
189        frame.extend_from_slice(&[PROTOCOL_VERSION, kind as u8]);
190        frame.extend_from_slice(&self.sent.to_be_bytes());
191        frame.extend_from_slice(payload);
192        let mut mac = self.frame_mac(self.role);
193        mac.update(&frame);
194        frame.extend_from_slice(&mac.finalize().into_bytes());
195        self.sent = next;
196        Ok(frame)
197    }
198
199    /// Verify an envelope from the peer and return its kind and payload
200    ///
201    /// The complete envelope is checked (size, version, kind, sequence, and
202    /// tag) before any of the payload is returned, so callers never parse
203    /// unauthenticated bytes. On success the receive sequence advances; on
204    /// failure the session state is unchanged and the caller should close
205    /// the connection.
206    pub fn open<'a>(&mut self, frame: &'a [u8]) -> Result<(FrameKind, &'a [u8]), Error> {
207        if frame.len() < ENVELOPE_OVERHEAD || frame[0] != PROTOCOL_VERSION {
208            return Err(Error::InvalidFrame);
209        }
210        let kind = FrameKind::from_byte(frame[1]).ok_or(Error::InvalidFrame)?;
211        let payload_len = frame.len() - ENVELOPE_OVERHEAD;
212        if frame.len() > MAX_MESSAGE || (kind == FrameKind::Text && payload_len > MAX_CONTROL) {
213            return Err(Error::FrameTooLarge);
214        }
215        let mut sequence = [0; 8];
216        sequence.copy_from_slice(&frame[2..HEADER_LEN]);
217        if u64::from_be_bytes(sequence) != self.received {
218            return Err(Error::OutOfSequence);
219        }
220        let tag_start = frame.len() - TAG_LEN;
221        let mut mac = self.frame_mac(self.role.peer());
222        mac.update(&frame[..tag_start]);
223        mac.verify_slice(&frame[tag_start..])
224            .map_err(|_| Error::InvalidMac)?;
225        self.received = self
226            .received
227            .checked_add(1)
228            .ok_or(Error::SequenceExhausted)?;
229        Ok((kind, &frame[HEADER_LEN..tag_start]))
230    }
231}
232
233impl std::fmt::Debug for Session {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct("Session")
236            .field("role", &self.role)
237            .field("sent", &self.sent)
238            .field("received", &self.received)
239            .finish_non_exhaustive()
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    fn pair() -> (Session, Session) {
248        (
249            Session::new("secret".into(), [1; 32], [2; 32], Role::Server),
250            Session::new("secret".into(), [1; 32], [2; 32], Role::Client),
251        )
252    }
253
254    #[test]
255    fn proofs_bind_both_nonces_roles_and_secret() {
256        let (client, server) = ([1; 32], [2; 32]);
257        let tag = proof("secret", Role::Server, &client, &server);
258        assert!(verify_proof("secret", Role::Server, &client, &server, &tag));
259        assert!(!verify_proof("other", Role::Server, &client, &server, &tag));
260        assert!(!verify_proof(
261            "secret",
262            Role::Client,
263            &client,
264            &server,
265            &tag
266        ));
267        assert!(!verify_proof(
268            "secret",
269            Role::Server,
270            &[3; 32],
271            &server,
272            &tag
273        ));
274        assert!(!verify_proof(
275            "secret",
276            Role::Server,
277            &client,
278            &[3; 32],
279            &tag
280        ));
281        assert!(!verify_proof("", Role::Server, &client, &server, &tag));
282    }
283
284    #[test]
285    fn envelopes_reject_tampering_reflection_replay_and_other_sessions() {
286        let (mut sender, mut receiver) = pair();
287        let frame = sender
288            .seal(FrameKind::Patch, b"patch metadata and library")
289            .unwrap();
290        for index in [0, 1, 2, 10, frame.len() - 1] {
291            let mut modified = frame.clone();
292            modified[index] ^= 1;
293            assert!(pair().1.open(&modified).is_err());
294        }
295        assert!(matches!(sender.open(&frame), Err(Error::InvalidMac)));
296        let mut other = Session::new("secret".into(), [3; 32], [2; 32], Role::Client);
297        assert!(matches!(other.open(&frame), Err(Error::InvalidMac)));
298        assert_eq!(
299            receiver.open(&frame).unwrap(),
300            (FrameKind::Patch, b"patch metadata and library".as_slice())
301        );
302        assert!(matches!(receiver.open(&frame), Err(Error::OutOfSequence)));
303        let next = sender.seal(FrameKind::Text, b"control").unwrap();
304        assert_eq!(
305            receiver.open(&next).unwrap(),
306            (FrameKind::Text, b"control".as_slice())
307        );
308    }
309
310    #[test]
311    fn bounds_and_sequence_exhaustion_fail_closed() {
312        let (mut sender, mut receiver) = pair();
313        assert!(sender.seal(FrameKind::Text, &vec![0; MAX_CONTROL]).is_ok());
314        assert!(matches!(
315            sender.seal(FrameKind::Text, &vec![0; MAX_CONTROL + 1]),
316            Err(Error::FrameTooLarge)
317        ));
318        assert!(matches!(
319            receiver.open(&[0; ENVELOPE_OVERHEAD - 1]),
320            Err(Error::InvalidFrame)
321        ));
322        let mut unknown_kind = vec![PROTOCOL_VERSION, 9];
323        unknown_kind.resize(ENVELOPE_OVERHEAD, 0);
324        assert!(matches!(
325            receiver.open(&unknown_kind),
326            Err(Error::InvalidFrame)
327        ));
328        let mut oversized_control = vec![PROTOCOL_VERSION, FrameKind::Text as u8];
329        oversized_control.resize(ENVELOPE_OVERHEAD + MAX_CONTROL + 1, 0);
330        assert!(matches!(
331            receiver.open(&oversized_control),
332            Err(Error::FrameTooLarge)
333        ));
334        sender.sent = u64::MAX;
335        assert!(matches!(
336            sender.seal(FrameKind::Patch, b"patch"),
337            Err(Error::SequenceExhausted)
338        ));
339    }
340
341    #[test]
342    fn debug_output_omits_the_secret() {
343        assert!(!format!("{:?}", pair().0).contains("secret"));
344    }
345}