Encrypt+MAC most P2P messages in-place
[rust-lightning] / lightning / src / util / chacha20poly1305rfc.rs
1 // ring has a garbage API so its use is avoided, but rust-crypto doesn't have RFC-variant poly1305
2 // Instead, we steal rust-crypto's implementation and tweak it to match the RFC.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9 //
10 // This is a port of Andrew Moons poly1305-donna
11 // https://github.com/floodyberry/poly1305-donna
12
13 use ln::msgs::DecodeError;
14 use util::ser::{FixedLengthReader, LengthRead, LengthReadableArgs, Readable, Writeable, Writer};
15 use io::{self, Read, Write};
16
17 #[cfg(not(fuzzing))]
18 mod real_chachapoly {
19         use util::chacha20::ChaCha20;
20         use util::poly1305::Poly1305;
21         use bitcoin::hashes::cmp::fixed_time_eq;
22
23         #[derive(Clone, Copy)]
24         pub struct ChaCha20Poly1305RFC {
25                 cipher: ChaCha20,
26                 mac: Poly1305,
27                 finished: bool,
28                 data_len: usize,
29                 aad_len: u64,
30         }
31
32         impl ChaCha20Poly1305RFC {
33                 #[inline]
34                 fn pad_mac_16(mac: &mut Poly1305, len: usize) {
35                         if len % 16 != 0 {
36                                 mac.input(&[0; 16][0..16 - (len % 16)]);
37                         }
38                 }
39                 pub fn new(key: &[u8], nonce: &[u8], aad: &[u8]) -> ChaCha20Poly1305RFC {
40                         assert!(key.len() == 16 || key.len() == 32);
41                         assert!(nonce.len() == 12);
42
43                         // Ehh, I'm too lazy to *also* tweak ChaCha20 to make it RFC-compliant
44                         assert!(nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0);
45
46                         let mut cipher = ChaCha20::new(key, &nonce[4..]);
47                         let mut mac_key = [0u8; 64];
48                         let zero_key = [0u8; 64];
49                         cipher.process(&zero_key, &mut mac_key);
50
51                         let mut mac = Poly1305::new(&mac_key[..32]);
52                         mac.input(aad);
53                         ChaCha20Poly1305RFC::pad_mac_16(&mut mac, aad.len());
54
55                         ChaCha20Poly1305RFC {
56                                 cipher,
57                                 mac,
58                                 finished: false,
59                                 data_len: 0,
60                                 aad_len: aad.len() as u64,
61                         }
62                 }
63
64                 pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) {
65                         assert!(input.len() == output.len());
66                         assert!(self.finished == false);
67                         self.cipher.process(input, output);
68                         self.data_len += input.len();
69                         self.mac.input(output);
70                         ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
71                         self.finished = true;
72                         self.mac.input(&self.aad_len.to_le_bytes());
73                         self.mac.input(&(self.data_len as u64).to_le_bytes());
74                         self.mac.raw_result(out_tag);
75                 }
76
77                 pub fn encrypt_full_message_in_place(&mut self, input_output: &mut [u8], out_tag: &mut [u8]) {
78                         self.encrypt_in_place(input_output);
79                         self.finish_and_get_tag(out_tag);
80                 }
81
82                 // Encrypt `input_output` in-place. To finish and calculate the tag, use `finish_and_get_tag`
83                 // below.
84                 pub(super) fn encrypt_in_place(&mut self, input_output: &mut [u8]) {
85                         debug_assert!(self.finished == false);
86                         self.cipher.process_in_place(input_output);
87                         self.data_len += input_output.len();
88                         self.mac.input(input_output);
89                 }
90
91                 // If we were previously encrypting with `encrypt_in_place`, this method can be used to finish
92                 // encrypting and calculate the tag.
93                 pub(super) fn finish_and_get_tag(&mut self, out_tag: &mut [u8]) {
94                         debug_assert!(self.finished == false);
95                         ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
96                         self.finished = true;
97                         self.mac.input(&self.aad_len.to_le_bytes());
98                         self.mac.input(&(self.data_len as u64).to_le_bytes());
99                         self.mac.raw_result(out_tag);
100                 }
101
102                 pub fn decrypt(&mut self, input: &[u8], output: &mut [u8], tag: &[u8]) -> bool {
103                         assert!(input.len() == output.len());
104                         assert!(self.finished == false);
105
106                         self.finished = true;
107
108                         self.mac.input(input);
109
110                         self.data_len += input.len();
111                         ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
112                         self.mac.input(&self.aad_len.to_le_bytes());
113                         self.mac.input(&(self.data_len as u64).to_le_bytes());
114
115                         let mut calc_tag =  [0u8; 16];
116                         self.mac.raw_result(&mut calc_tag);
117                         if fixed_time_eq(&calc_tag, tag) {
118                                 self.cipher.process(input, output);
119                                 true
120                         } else {
121                                 false
122                         }
123                 }
124
125                 // Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it
126                 // later when decryption finishes.
127                 //
128                 // Should never be `pub` because the public API should always enforce tag checking.
129                 pub(super) fn decrypt_in_place(&mut self, input_output: &mut [u8]) {
130                         debug_assert!(self.finished == false);
131                         self.mac.input(input_output);
132                         self.data_len += input_output.len();
133                         self.cipher.process_in_place(input_output);
134                 }
135
136                 // If we were previously decrypting with `decrypt_in_place`, this method must be used to finish
137                 // decrypting and check the tag. Returns whether or not the tag is valid.
138                 pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
139                         debug_assert!(self.finished == false);
140                         self.finished = true;
141                         ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
142                         self.mac.input(&self.aad_len.to_le_bytes());
143                         self.mac.input(&(self.data_len as u64).to_le_bytes());
144
145                         let mut calc_tag =  [0u8; 16];
146                         self.mac.raw_result(&mut calc_tag);
147                         if fixed_time_eq(&calc_tag, tag) {
148                                 true
149                         } else {
150                                 false
151                         }
152                 }
153         }
154 }
155 #[cfg(not(fuzzing))]
156 pub use self::real_chachapoly::ChaCha20Poly1305RFC;
157
158 /// Enables simultaneously reading and decrypting a ChaCha20Poly1305RFC stream from a std::io::Read.
159 struct ChaChaPolyReader<'a, R: Read> {
160         pub chacha: &'a mut ChaCha20Poly1305RFC,
161         pub read: R,
162 }
163
164 impl<'a, R: Read> Read for ChaChaPolyReader<'a, R> {
165         // Decrypt bytes from Self::read into `dest`.
166         // `ChaCha20Poly1305RFC::finish_and_check_tag` must be called to check the tag after all reads
167         // complete.
168         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
169                 let res = self.read.read(dest)?;
170                 if res > 0 {
171                         self.chacha.decrypt_in_place(&mut dest[0..res]);
172                 }
173                 Ok(res)
174         }
175 }
176
177 /// Enables simultaneously writing and encrypting a byte stream into a Writer.
178 struct ChaChaPolyWriter<'a, W: Writer> {
179         pub chacha: &'a mut ChaCha20Poly1305RFC,
180         pub write: &'a mut W,
181 }
182
183 impl<'a, W: Writer> Writer for ChaChaPolyWriter<'a, W> {
184         // Encrypt then write bytes from `src` into Self::write.
185         // `ChaCha20Poly1305RFC::finish_and_get_tag` can be called to retrieve the tag after all writes
186         // complete.
187         fn write_all(&mut self, src: &[u8]) -> Result<(), io::Error> {
188                 let mut src_idx = 0;
189                 while src_idx < src.len() {
190                         let mut write_buffer = [0; 8192];
191                         let bytes_written = (&mut write_buffer[..]).write(&src[src_idx..]).expect("In-memory writes can't fail");
192                         self.chacha.encrypt_in_place(&mut write_buffer[..bytes_written]);
193                         self.write.write_all(&write_buffer[..bytes_written])?;
194                         src_idx += bytes_written;
195                 }
196                 Ok(())
197         }
198 }
199
200 /// Enables the use of the serialization macros for objects that need to be simultaneously encrypted and
201 /// serialized. This allows us to avoid an intermediate Vec allocation.
202 pub(crate) struct ChaChaPolyWriteAdapter<'a, W: Writeable> {
203         pub rho: [u8; 32],
204         pub writeable: &'a W,
205 }
206
207 impl<'a, W: Writeable> ChaChaPolyWriteAdapter<'a, W> {
208         #[allow(unused)] // This will be used for onion messages soon
209         pub fn new(rho: [u8; 32], writeable: &'a W) -> ChaChaPolyWriteAdapter<'a, W> {
210                 Self { rho, writeable }
211         }
212 }
213
214 impl<'a, T: Writeable> Writeable for ChaChaPolyWriteAdapter<'a, T> {
215         // Simultaneously write and encrypt Self::writeable.
216         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
217                 let mut chacha = ChaCha20Poly1305RFC::new(&self.rho, &[0; 12], &[]);
218                 let mut chacha_stream = ChaChaPolyWriter { chacha: &mut chacha, write: w };
219                 self.writeable.write(&mut chacha_stream)?;
220                 let mut tag = [0 as u8; 16];
221                 chacha.finish_and_get_tag(&mut tag);
222                 tag.write(w)?;
223
224                 Ok(())
225         }
226 }
227
228 /// Enables the use of the serialization macros for objects that need to be simultaneously decrypted and
229 /// deserialized. This allows us to avoid an intermediate Vec allocation.
230 pub(crate) struct ChaChaPolyReadAdapter<R: Readable> {
231         #[allow(unused)] // This will be used soon for onion messages
232         pub readable: R,
233 }
234
235 impl<T: Readable> LengthReadableArgs<[u8; 32]> for ChaChaPolyReadAdapter<T> {
236         // Simultaneously read and decrypt an object from a LengthRead, storing it in Self::readable.
237         // LengthRead must be used instead of std::io::Read because we need the total length to separate
238         // out the tag at the end.
239         fn read<R: LengthRead>(mut r: &mut R, secret: [u8; 32]) -> Result<Self, DecodeError> {
240                 if r.total_bytes() < 16 { return Err(DecodeError::InvalidValue) }
241
242                 let mut chacha = ChaCha20Poly1305RFC::new(&secret, &[0; 12], &[]);
243                 let decrypted_len = r.total_bytes() - 16;
244                 let s = FixedLengthReader::new(&mut r, decrypted_len);
245                 let mut chacha_stream = ChaChaPolyReader { chacha: &mut chacha, read: s };
246                 let readable: T = Readable::read(&mut chacha_stream)?;
247                 chacha_stream.read.eat_remaining()?;
248
249                 let mut tag = [0 as u8; 16];
250                 r.read_exact(&mut tag)?;
251                 if !chacha.finish_and_check_tag(&tag) {
252                         return Err(DecodeError::InvalidValue)
253                 }
254
255                 Ok(Self { readable })
256         }
257 }
258
259 #[cfg(fuzzing)]
260 mod fuzzy_chachapoly {
261         #[derive(Clone, Copy)]
262         pub struct ChaCha20Poly1305RFC {
263                 tag: [u8; 16],
264                 finished: bool,
265         }
266         impl ChaCha20Poly1305RFC {
267                 pub fn new(key: &[u8], nonce: &[u8], _aad: &[u8]) -> ChaCha20Poly1305RFC {
268                         assert!(key.len() == 16 || key.len() == 32);
269                         assert!(nonce.len() == 12);
270
271                         // Ehh, I'm too lazy to *also* tweak ChaCha20 to make it RFC-compliant
272                         assert!(nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0);
273
274                         let mut tag = [0; 16];
275                         tag.copy_from_slice(&key[0..16]);
276
277                         ChaCha20Poly1305RFC {
278                                 tag,
279                                 finished: false,
280                         }
281                 }
282
283                 pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) {
284                         assert!(input.len() == output.len());
285                         assert!(self.finished == false);
286
287                         output.copy_from_slice(&input);
288                         out_tag.copy_from_slice(&self.tag);
289                         self.finished = true;
290                 }
291
292                 pub fn encrypt_full_message_in_place(&mut self, input_output: &mut [u8], out_tag: &mut [u8]) {
293                         self.encrypt_in_place(input_output);
294                         self.finish_and_get_tag(out_tag);
295                 }
296
297                 pub(super) fn encrypt_in_place(&mut self, _input_output: &mut [u8]) {
298                         assert!(self.finished == false);
299                 }
300
301                 pub(super) fn finish_and_get_tag(&mut self, out_tag: &mut [u8]) {
302                         assert!(self.finished == false);
303                         out_tag.copy_from_slice(&self.tag);
304                         self.finished = true;
305                 }
306
307                 pub fn decrypt(&mut self, input: &[u8], output: &mut [u8], tag: &[u8]) -> bool {
308                         assert!(input.len() == output.len());
309                         assert!(self.finished == false);
310
311                         if tag[..] != self.tag[..] { return false; }
312                         output.copy_from_slice(input);
313                         self.finished = true;
314                         true
315                 }
316
317                 pub(super) fn decrypt_in_place(&mut self, _input: &mut [u8]) {
318                         assert!(self.finished == false);
319                 }
320
321                 pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
322                         if tag[..] != self.tag[..] { return false; }
323                         self.finished = true;
324                         true
325                 }
326         }
327 }
328 #[cfg(fuzzing)]
329 pub use self::fuzzy_chachapoly::ChaCha20Poly1305RFC;
330
331 #[cfg(test)]
332 mod tests {
333         use ln::msgs::DecodeError;
334         use super::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
335         use util::ser::{self, FixedLengthReader, LengthReadableArgs, Writeable};
336
337         // Used for for testing various lengths of serialization.
338         #[derive(Debug, PartialEq)]
339         struct TestWriteable {
340                 field1: Vec<u8>,
341                 field2: Vec<u8>,
342                 field3: Vec<u8>,
343         }
344         impl_writeable_tlv_based!(TestWriteable, {
345                 (1, field1, vec_type),
346                 (2, field2, vec_type),
347                 (3, field3, vec_type),
348         });
349
350         #[test]
351         fn test_chacha_stream_adapters() {
352                 // Check that ChaChaPolyReadAdapter and ChaChaPolyWriteAdapter correctly encode and decode an
353                 // encrypted object.
354                 macro_rules! check_object_read_write {
355                         ($obj: expr) => {
356                                 // First, serialize the object, encrypted with ChaCha20Poly1305.
357                                 let rho = [42; 32];
358                                 let writeable_len = $obj.serialized_length() as u64 + 16;
359                                 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &$obj);
360                                 let encrypted_writeable_bytes = write_adapter.encode();
361                                 let encrypted_writeable = &encrypted_writeable_bytes[..];
362
363                                 // Now deserialize the object back and make sure it matches the original.
364                                 let mut rd = FixedLengthReader::new(encrypted_writeable, writeable_len);
365                                 let read_adapter = <ChaChaPolyReadAdapter<TestWriteable>>::read(&mut rd, rho).unwrap();
366                                 assert_eq!($obj, read_adapter.readable);
367                         };
368                 }
369
370                 // Try a big object that will require multiple write buffers.
371                 let big_writeable = TestWriteable {
372                         field1: vec![43],
373                         field2: vec![44; 4192],
374                         field3: vec![45; 4192 + 1],
375                 };
376                 check_object_read_write!(big_writeable);
377
378                 // Try a small object that fits into one write buffer.
379                 let small_writeable = TestWriteable {
380                         field1: vec![43],
381                         field2: vec![44],
382                         field3: vec![45],
383                 };
384                 check_object_read_write!(small_writeable);
385         }
386
387         fn do_chacha_stream_adapters_ser_macros() -> Result<(), DecodeError> {
388                 let writeable = TestWriteable {
389                         field1: vec![43],
390                         field2: vec![44; 4192],
391                         field3: vec![45; 4192 + 1],
392                 };
393
394                 // First, serialize the object into a TLV stream, encrypted with ChaCha20Poly1305.
395                 let rho = [42; 32];
396                 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &writeable);
397                 let mut writer = ser::VecWriter(Vec::new());
398                 encode_tlv_stream!(&mut writer, {
399                         (1, write_adapter, required),
400                 });
401
402                 // Now deserialize the object back and make sure it matches the original.
403                 let mut read_adapter: Option<ChaChaPolyReadAdapter<TestWriteable>> = None;
404                 decode_tlv_stream!(&writer.0[..], {
405                         (1, read_adapter, (option: LengthReadableArgs, rho)),
406                 });
407                 assert_eq!(writeable, read_adapter.unwrap().readable);
408
409                 Ok(())
410         }
411
412         #[test]
413         fn chacha_stream_adapters_ser_macros() {
414                 // Test that our stream adapters work as expected with the TLV macros.
415                 // This also serves to test the `option: $trait` variant of the `decode_tlv` ser macro.
416                 do_chacha_stream_adapters_ser_macros().unwrap()
417         }
418 }