Skip to main content

whisker_dev_protocol/
handshake.rs

1//! Mutual-authentication handshake state machines.
2
3use serde::{Deserialize, Serialize};
4
5use crate::session::{Role, Session, proof, verify_proof};
6use crate::{Error, MAX_HANDSHAKE, PROTOCOL_VERSION, random_bytes};
7
8#[derive(Serialize, Deserialize)]
9#[serde(deny_unknown_fields)]
10struct Challenge {
11    version: u8,
12    nonce: [u8; 32],
13}
14
15#[derive(Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17struct ServerProof {
18    nonce: [u8; 32],
19    mac: [u8; 32],
20}
21
22#[derive(Serialize, Deserialize)]
23#[serde(deny_unknown_fields)]
24struct ClientProof {
25    mac: [u8; 32],
26}
27
28fn parse<'a, T: Deserialize<'a>>(text: &'a str) -> Result<T, Error> {
29    if text.len() > MAX_HANDSHAKE {
30        return Err(Error::HandshakeTooLarge);
31    }
32    serde_json::from_str(text).map_err(Error::MalformedHandshake)
33}
34
35fn encode<T: Serialize>(message: &T) -> Result<String, Error> {
36    serde_json::to_string(message).map_err(Error::MalformedHandshake)
37}
38
39/// Client (app) side of the handshake, between the challenge and the server proof
40///
41/// The dev runtime calls [`start`](Self::start), sends the returned
42/// challenge as a WebSocket text message, waits for the server's text reply,
43/// and passes it to [`finish`](Self::finish). Only after `finish` succeeds
44/// does the app send its proof and then anything identifying the process.
45///
46/// # Example
47///
48/// ```rust
49/// use whisker_dev_protocol::{ClientHandshake, Error, ServerHandshake};
50///
51/// let (client, challenge) = ClientHandshake::start("app secret")?;
52/// // A server from another session holds a different secret.
53/// let (_server, proof) = ServerHandshake::respond("other secret", &challenge)?;
54/// assert!(matches!(client.finish(&proof), Err(Error::InvalidServerProof)));
55/// # Ok::<(), Error>(())
56/// ```
57pub struct ClientHandshake {
58    secret: String,
59    nonce: [u8; 32],
60}
61
62impl ClientHandshake {
63    /// Begin a handshake and return the challenge text to send
64    ///
65    /// Fails with [`Error::MissingSecret`] for an empty secret and with
66    /// [`Error::Random`] if no nonce can be generated.
67    pub fn start(secret: &str) -> Result<(Self, String), Error> {
68        if secret.is_empty() {
69            return Err(Error::MissingSecret);
70        }
71        let nonce = random_bytes()?;
72        let challenge = encode(&Challenge {
73            version: PROTOCOL_VERSION,
74            nonce,
75        })?;
76        Ok((
77            Self {
78                secret: secret.to_owned(),
79                nonce,
80            },
81            challenge,
82        ))
83    }
84
85    /// Verify the server's proof and return the session plus the client proof to send
86    ///
87    /// Fails with [`Error::InvalidServerProof`] when the server does not hold
88    /// the same secret, which is what an app left over from a previous
89    /// `whisker run` session observes.
90    pub fn finish(self, server_proof: &str) -> Result<(Session, String), Error> {
91        let server: ServerProof = parse(server_proof)?;
92        if !verify_proof(
93            &self.secret,
94            Role::Server,
95            &self.nonce,
96            &server.nonce,
97            &server.mac,
98        ) {
99            return Err(Error::InvalidServerProof);
100        }
101        let reply = encode(&ClientProof {
102            mac: proof(&self.secret, Role::Client, &self.nonce, &server.nonce),
103        })?;
104        Ok((
105            Session::new(self.secret, self.nonce, server.nonce, Role::Client),
106            reply,
107        ))
108    }
109}
110
111/// Server (`whisker run`) side of the handshake, between the server proof and the client proof
112///
113/// The dev server passes the first text message it receives to
114/// [`respond`](Self::respond), sends the returned proof, and then sends
115/// nothing else until [`finish`](Self::finish) accepts the client's proof.
116/// The dev runtime relies on that silence to bound how much it reads before
117/// authentication.
118///
119/// # Example
120///
121/// ```rust
122/// use whisker_dev_protocol::{Error, ServerHandshake};
123///
124/// // A pre-handshake hello that carries the secret is not a challenge.
125/// let legacy = r#"{"kind":"hello","aslr_reference":1,"token":"secret"}"#;
126/// assert!(matches!(
127///     ServerHandshake::respond("secret", legacy),
128///     Err(Error::MalformedHandshake(_))
129/// ));
130/// ```
131pub struct ServerHandshake {
132    secret: String,
133    client_nonce: [u8; 32],
134    server_nonce: [u8; 32],
135}
136
137impl ServerHandshake {
138    /// Check a client challenge and return the server proof text to send
139    ///
140    /// Fails with [`Error::UnsupportedVersion`] for a challenge from another
141    /// protocol version and [`Error::MalformedHandshake`] for anything that
142    /// is not a challenge.
143    pub fn respond(secret: &str, challenge: &str) -> Result<(Self, String), Error> {
144        if secret.is_empty() {
145            return Err(Error::MissingSecret);
146        }
147        #[derive(Deserialize)]
148        struct Version {
149            version: u8,
150        }
151        if let Ok(Version { version }) = parse(challenge) {
152            if version != PROTOCOL_VERSION {
153                return Err(Error::UnsupportedVersion(version));
154            }
155        }
156        let challenge: Challenge = parse(challenge)?;
157        let server_nonce = random_bytes()?;
158        let reply = encode(&ServerProof {
159            nonce: server_nonce,
160            mac: proof(secret, Role::Server, &challenge.nonce, &server_nonce),
161        })?;
162        Ok((
163            Self {
164                secret: secret.to_owned(),
165                client_nonce: challenge.nonce,
166                server_nonce,
167            },
168            reply,
169        ))
170    }
171
172    /// Verify the client's proof and return the established session
173    ///
174    /// Fails with [`Error::InvalidClientProof`] when the client does not
175    /// hold the same secret.
176    pub fn finish(self, client_proof: &str) -> Result<Session, Error> {
177        let client: ClientProof = parse(client_proof)?;
178        if !verify_proof(
179            &self.secret,
180            Role::Client,
181            &self.client_nonce,
182            &self.server_nonce,
183            &client.mac,
184        ) {
185            return Err(Error::InvalidClientProof);
186        }
187        Ok(Session::new(
188            self.secret,
189            self.client_nonce,
190            self.server_nonce,
191            Role::Server,
192        ))
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::FrameKind;
200
201    #[test]
202    fn matching_secrets_establish_paired_sessions() {
203        let (client, challenge) = ClientHandshake::start("secret").unwrap();
204        assert!(!challenge.contains("secret"));
205        let (server, server_proof) = ServerHandshake::respond("secret", &challenge).unwrap();
206        let (mut app, client_proof) = client.finish(&server_proof).unwrap();
207        let mut host = server.finish(&client_proof).unwrap();
208        let frame = host.seal(FrameKind::Patch, b"library").unwrap();
209        assert_eq!(
210            app.open(&frame).unwrap(),
211            (FrameKind::Patch, b"library".as_slice())
212        );
213        let frame = app.seal(FrameKind::Text, b"hello").unwrap();
214        assert_eq!(
215            host.open(&frame).unwrap(),
216            (FrameKind::Text, b"hello".as_slice())
217        );
218    }
219
220    #[test]
221    fn mismatched_secrets_fail_on_both_sides() {
222        let (client, challenge) = ClientHandshake::start("app").unwrap();
223        let (_, server_proof) = ServerHandshake::respond("host", &challenge).unwrap();
224        assert!(matches!(
225            client.finish(&server_proof),
226            Err(Error::InvalidServerProof)
227        ));
228
229        let (client, challenge) = ClientHandshake::start("secret").unwrap();
230        let (server, server_proof) = ServerHandshake::respond("secret", &challenge).unwrap();
231        let (_, client_proof) = client.finish(&server_proof).unwrap();
232        let (other, _) = ServerHandshake::respond("secret", &challenge).unwrap();
233        assert!(matches!(
234            other.finish(&client_proof),
235            Err(Error::InvalidClientProof)
236        ));
237        assert!(server.finish(&client_proof).is_ok());
238    }
239
240    #[test]
241    fn invalid_handshake_messages_are_rejected() {
242        assert!(matches!(
243            ClientHandshake::start(""),
244            Err(Error::MissingSecret)
245        ));
246        assert!(matches!(
247            ServerHandshake::respond("", "{}"),
248            Err(Error::MissingSecret)
249        ));
250        let future = format!(r#"{{"version":2,"nonce":{:?}}}"#, [0u8; 32]);
251        assert!(matches!(
252            ServerHandshake::respond("secret", &future),
253            Err(Error::UnsupportedVersion(2))
254        ));
255        assert!(matches!(
256            ServerHandshake::respond("secret", r#"{"kind":"hello","aslr_reference":1}"#),
257            Err(Error::MalformedHandshake(_))
258        ));
259        let padded = format!("{}{}", " ".repeat(MAX_HANDSHAKE), "{}");
260        assert!(matches!(
261            ServerHandshake::respond("secret", &padded),
262            Err(Error::HandshakeTooLarge)
263        ));
264        let (client, _) = ClientHandshake::start("secret").unwrap();
265        assert!(matches!(
266            client.finish(&padded),
267            Err(Error::HandshakeTooLarge)
268        ));
269    }
270}