tlspuffin/tls/rustls/
hash_hs.rs

1use std::{fmt, mem};
2
3use comparable::Comparable;
4use puffin::codec;
5use puffin::codec::{Codec, Reader};
6use ring::digest;
7
8use crate::tls::rustls::msgs::handshake::HandshakeMessagePayload;
9use crate::tls::rustls::msgs::message::{Message, MessagePayload};
10
11/// Early stage buffering of handshake payloads.
12///
13/// Before we know the hash algorithm to use to verify the handshake, we just buffer the messages.
14/// During the handshake, we may restart the transcript due to a HelloRetryRequest, reverting
15/// from the `HandshakeHash` to a `HandshakeHashBuffer` again.
16#[derive(Default, Clone)]
17pub struct HandshakeHashBuffer {
18    buffer: Vec<u8>,
19    client_auth_enabled: bool,
20}
21
22impl HandshakeHashBuffer {
23    pub fn new() -> Self {
24        Self {
25            buffer: Vec::new(),
26            client_auth_enabled: false,
27        }
28    }
29
30    /// We might be doing client auth, so need to keep a full
31    /// log of the handshake.
32    pub fn set_client_auth_enabled(&mut self) {
33        self.client_auth_enabled = true;
34    }
35
36    /// Hash/buffer a handshake message.
37    pub fn add_message(&mut self, m: &Message) {
38        if let MessagePayload::Handshake(hs) = &m.payload {
39            self.buffer.extend_from_slice(&hs.get_encoding());
40        }
41    }
42
43    /// Hash or buffer a byte slice.
44    #[cfg(test)]
45    fn update_raw(&mut self, buf: &[u8]) {
46        self.buffer.extend_from_slice(buf);
47    }
48
49    /// Get the hash value if we were to hash `extra` too.
50    pub fn get_hash_given(&self, hash: &'static digest::Algorithm, extra: &[u8]) -> digest::Digest {
51        let mut ctx = digest::Context::new(hash);
52        ctx.update(&self.buffer);
53        ctx.update(extra);
54        ctx.finish()
55    }
56
57    /// We now know what hash function the verify_data will use.
58    pub fn start_hash(self, alg: &'static digest::Algorithm) -> HandshakeHash {
59        let mut ctx = digest::Context::new(alg);
60        ctx.update(&self.buffer);
61        HandshakeHash {
62            ctx,
63            client_auth: match self.client_auth_enabled {
64                true => Some(self.buffer),
65                false => None,
66            },
67            override_buffer: None,
68        }
69    }
70}
71
72/// This deals with keeping a running hash of the handshake
73/// payloads.  This is computed by buffering initially.  Once
74/// we know what hash function we need to use we switch to
75/// incremental hashing.
76///
77/// For client auth, we also need to buffer all the messages.
78/// This is disabled in cases where client auth is not possible.
79#[derive(Clone, Comparable)]
80pub struct HandshakeHash {
81    /// None before we know what hash function we're using
82    #[comparable_ignore]
83    ctx: digest::Context,
84
85    /// buffer for client-auth.
86    client_auth: Option<Vec<u8>>,
87
88    override_buffer: Option<Vec<u8>>,
89}
90
91impl fmt::Debug for HandshakeHash {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        writeln!(f, "HandshakeHash: {:?}", codec::Codec::get_encoding(self))
94    }
95}
96
97impl codec::Codec for HandshakeHash {
98    fn encode(&self, bytes: &mut Vec<u8>) {
99        // TODO-bitlevel: not sure this is the way this should be encoded!! (to test!)
100        let mut hash = self.get_current_hash_raw();
101        bytes.append(&mut hash)
102    }
103
104    fn read(r: &mut Reader) -> Option<Self> {
105        Some(HandshakeHash::new_override(
106            r.rest().to_vec(),
107            &ring::digest::SHA256,
108        ))
109    }
110}
111
112impl HandshakeHash {
113    pub fn new(alg: &'static digest::Algorithm) -> HandshakeHash {
114        let ctx = digest::Context::new(alg);
115        HandshakeHash {
116            ctx,
117            client_auth: None,
118            override_buffer: None,
119        }
120    }
121
122    /// Creates a Handshake hash which return the same override hash always
123    pub fn new_override(static_buffer: Vec<u8>, alg: &'static digest::Algorithm) -> HandshakeHash {
124        let ctx = digest::Context::new(alg);
125        HandshakeHash {
126            ctx,
127            client_auth: None,
128            override_buffer: Some(static_buffer),
129        }
130    }
131
132    /// We decided not to do client auth after all, so discard
133    /// the transcript.
134    pub fn abandon_client_auth(&mut self) {
135        self.client_auth = None;
136    }
137
138    /// Hash/buffer a handshake message.
139    pub fn add_message(&mut self, m: &Message) -> &mut Self {
140        if let MessagePayload::Handshake(hs) = &m.payload {
141            let buf = hs.get_encoding();
142            self.update_raw(&buf);
143        }
144        self
145    }
146
147    /// Hash or buffer a byte slice.
148    fn update_raw(&mut self, buf: &[u8]) -> &mut Self {
149        self.ctx.update(buf);
150
151        if let Some(buffer) = &mut self.client_auth {
152            buffer.extend_from_slice(buf);
153        }
154
155        self
156    }
157
158    /// Get the hash value if we were to hash `extra` too,
159    /// using hash function `hash`.
160    pub fn get_hash_given(&self, extra: &[u8]) -> digest::Digest {
161        let mut ctx = self.ctx.clone();
162        ctx.update(extra);
163        ctx.finish()
164    }
165
166    pub fn into_hrr_buffer(self) -> HandshakeHashBuffer {
167        let old_hash = self.ctx.finish();
168        let old_handshake_hash_msg =
169            HandshakeMessagePayload::build_handshake_hash(old_hash.as_ref());
170
171        HandshakeHashBuffer {
172            client_auth_enabled: self.client_auth.is_some(),
173            buffer: old_handshake_hash_msg.get_encoding(),
174        }
175    }
176
177    /// Take the current hash value, and encapsulate it in a
178    /// 'handshake_hash' handshake message.  Start this hash
179    /// again, with that message at the front.
180    pub fn rollup_for_hrr(&mut self) {
181        let ctx = &mut self.ctx;
182
183        let old_ctx = mem::replace(ctx, digest::Context::new(ctx.algorithm()));
184        let old_hash = old_ctx.finish();
185        let old_handshake_hash_msg =
186            HandshakeMessagePayload::build_handshake_hash(old_hash.as_ref());
187
188        self.update_raw(&old_handshake_hash_msg.get_encoding());
189    }
190
191    /// Get the current hash value.
192    pub fn get_current_hash(&self) -> digest::Digest {
193        self.ctx.clone().finish()
194    }
195
196    pub fn get_current_hash_raw(&self) -> Vec<u8> {
197        if let Some(static_buffer) = &self.override_buffer {
198            (*static_buffer).clone()
199        } else {
200            Vec::from(self.get_current_hash().as_ref())
201        }
202    }
203
204    /// Takes this object's buffer containing all handshake messages
205    /// so far.  This method only works once; it resets the buffer
206    /// to empty.
207    pub fn take_handshake_buf(&mut self) -> Option<Vec<u8>> {
208        self.client_auth.take()
209    }
210
211    /// The digest algorithm
212    pub fn algorithm(&self) -> &'static digest::Algorithm {
213        self.ctx.algorithm()
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use ring::digest;
220
221    use super::HandshakeHashBuffer;
222
223    #[test_log::test]
224    fn hashes_correctly() {
225        let mut hhb = HandshakeHashBuffer::new();
226        hhb.update_raw(b"hello");
227        assert_eq!(hhb.buffer.len(), 5);
228        let mut hh = hhb.start_hash(&digest::SHA256);
229        assert!(hh.client_auth.is_none());
230        hh.update_raw(b"world");
231        let h = hh.get_current_hash();
232        let h = h.as_ref();
233        assert_eq!(h[0], 0x93);
234        assert_eq!(h[1], 0x6a);
235        assert_eq!(h[2], 0x18);
236        assert_eq!(h[3], 0x5c);
237    }
238
239    #[test_log::test]
240    fn buffers_correctly() {
241        let mut hhb = HandshakeHashBuffer::new();
242        hhb.set_client_auth_enabled();
243        hhb.update_raw(b"hello");
244        assert_eq!(hhb.buffer.len(), 5);
245        let mut hh = hhb.start_hash(&digest::SHA256);
246        assert_eq!(hh.client_auth.as_ref().map(|buf| buf.len()), Some(5));
247        hh.update_raw(b"world");
248        assert_eq!(hh.client_auth.as_ref().map(|buf| buf.len()), Some(10));
249        let h = hh.get_current_hash();
250        let h = h.as_ref();
251        assert_eq!(h[0], 0x93);
252        assert_eq!(h[1], 0x6a);
253        assert_eq!(h[2], 0x18);
254        assert_eq!(h[3], 0x5c);
255        let buf = hh.take_handshake_buf();
256        assert_eq!(Some(b"helloworld".to_vec()), buf);
257    }
258
259    #[test_log::test]
260    fn abandon() {
261        let mut hhb = HandshakeHashBuffer::new();
262        hhb.set_client_auth_enabled();
263        hhb.update_raw(b"hello");
264        assert_eq!(hhb.buffer.len(), 5);
265        let mut hh = hhb.start_hash(&digest::SHA256);
266        assert_eq!(hh.client_auth.as_ref().map(|buf| buf.len()), Some(5));
267        hh.abandon_client_auth();
268        assert_eq!(hh.client_auth, None);
269        hh.update_raw(b"world");
270        assert_eq!(hh.client_auth, None);
271        let h = hh.get_current_hash();
272        let h = h.as_ref();
273        assert_eq!(h[0], 0x93);
274        assert_eq!(h[1], 0x6a);
275        assert_eq!(h[2], 0x18);
276        assert_eq!(h[3], 0x5c);
277    }
278}