]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/util/chacha20poly1305rfc.rs
Merge pull request #1951 from wpaulino/remove-get-node-secret
[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 crate::ln::msgs::DecodeError;
14 use crate::util::ser::{FixedLengthReader, LengthRead, LengthReadableArgs, Readable, Writeable, Writer};
15 use crate::io::{self, Read, Write};
16
17 #[cfg(not(fuzzing))]
18 mod real_chachapoly {
19         use crate::util::chacha20::ChaCha20;
20         use crate::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         pub readable: R,
232 }
233
234 impl<T: Readable> LengthReadableArgs<[u8; 32]> for ChaChaPolyReadAdapter<T> {
235         // Simultaneously read and decrypt an object from a LengthRead, storing it in Self::readable.
236         // LengthRead must be used instead of std::io::Read because we need the total length to separate
237         // out the tag at the end.
238         fn read<R: LengthRead>(mut r: &mut R, secret: [u8; 32]) -> Result<Self, DecodeError> {
239                 if r.total_bytes() < 16 { return Err(DecodeError::InvalidValue) }
240
241                 let mut chacha = ChaCha20Poly1305RFC::new(&secret, &[0; 12], &[]);
242                 let decrypted_len = r.total_bytes() - 16;
243                 let s = FixedLengthReader::new(&mut r, decrypted_len);
244                 let mut chacha_stream = ChaChaPolyReader { chacha: &mut chacha, read: s };
245                 let readable: T = Readable::read(&mut chacha_stream)?;
246                 chacha_stream.read.eat_remaining()?;
247
248                 let mut tag = [0 as u8; 16];
249                 r.read_exact(&mut tag)?;
250                 if !chacha.finish_and_check_tag(&tag) {
251                         return Err(DecodeError::InvalidValue)
252                 }
253
254                 Ok(Self { readable })
255         }
256 }
257
258 #[cfg(fuzzing)]
259 mod fuzzy_chachapoly {
260         #[derive(Clone, Copy)]
261         pub struct ChaCha20Poly1305RFC {
262                 tag: [u8; 16],
263                 finished: bool,
264         }
265         impl ChaCha20Poly1305RFC {
266                 pub fn new(key: &[u8], nonce: &[u8], _aad: &[u8]) -> ChaCha20Poly1305RFC {
267                         assert!(key.len() == 16 || key.len() == 32);
268                         assert!(nonce.len() == 12);
269
270                         // Ehh, I'm too lazy to *also* tweak ChaCha20 to make it RFC-compliant
271                         assert!(nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0);
272
273                         let mut tag = [0; 16];
274                         tag.copy_from_slice(&key[0..16]);
275
276                         ChaCha20Poly1305RFC {
277                                 tag,
278                                 finished: false,
279                         }
280                 }
281
282                 pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) {
283                         assert!(input.len() == output.len());
284                         assert!(self.finished == false);
285
286                         output.copy_from_slice(&input);
287                         out_tag.copy_from_slice(&self.tag);
288                         self.finished = true;
289                 }
290
291                 pub fn encrypt_full_message_in_place(&mut self, input_output: &mut [u8], out_tag: &mut [u8]) {
292                         self.encrypt_in_place(input_output);
293                         self.finish_and_get_tag(out_tag);
294                 }
295
296                 pub(super) fn encrypt_in_place(&mut self, _input_output: &mut [u8]) {
297                         assert!(self.finished == false);
298                 }
299
300                 pub(super) fn finish_and_get_tag(&mut self, out_tag: &mut [u8]) {
301                         assert!(self.finished == false);
302                         out_tag.copy_from_slice(&self.tag);
303                         self.finished = true;
304                 }
305
306                 pub fn decrypt(&mut self, input: &[u8], output: &mut [u8], tag: &[u8]) -> bool {
307                         assert!(input.len() == output.len());
308                         assert!(self.finished == false);
309
310                         if tag[..] != self.tag[..] { return false; }
311                         output.copy_from_slice(input);
312                         self.finished = true;
313                         true
314                 }
315
316                 pub(super) fn decrypt_in_place(&mut self, _input: &mut [u8]) {
317                         assert!(self.finished == false);
318                 }
319
320                 pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
321                         if tag[..] != self.tag[..] { return false; }
322                         self.finished = true;
323                         true
324                 }
325         }
326 }
327 #[cfg(fuzzing)]
328 pub use self::fuzzy_chachapoly::ChaCha20Poly1305RFC;
329
330 #[cfg(test)]
331 mod tests {
332         use crate::ln::msgs::DecodeError;
333         use super::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
334         use crate::util::ser::{self, FixedLengthReader, LengthReadableArgs, Writeable};
335
336         // Used for for testing various lengths of serialization.
337         #[derive(Debug, PartialEq, Eq)]
338         struct TestWriteable {
339                 field1: Vec<u8>,
340                 field2: Vec<u8>,
341                 field3: Vec<u8>,
342         }
343         impl_writeable_tlv_based!(TestWriteable, {
344                 (1, field1, vec_type),
345                 (2, field2, vec_type),
346                 (3, field3, vec_type),
347         });
348
349         #[test]
350         fn test_chacha_stream_adapters() {
351                 // Check that ChaChaPolyReadAdapter and ChaChaPolyWriteAdapter correctly encode and decode an
352                 // encrypted object.
353                 macro_rules! check_object_read_write {
354                         ($obj: expr) => {
355                                 // First, serialize the object, encrypted with ChaCha20Poly1305.
356                                 let rho = [42; 32];
357                                 let writeable_len = $obj.serialized_length() as u64 + 16;
358                                 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &$obj);
359                                 let encrypted_writeable_bytes = write_adapter.encode();
360                                 let encrypted_writeable = &encrypted_writeable_bytes[..];
361
362                                 // Now deserialize the object back and make sure it matches the original.
363                                 let mut rd = FixedLengthReader::new(encrypted_writeable, writeable_len);
364                                 let read_adapter = <ChaChaPolyReadAdapter<TestWriteable>>::read(&mut rd, rho).unwrap();
365                                 assert_eq!($obj, read_adapter.readable);
366                         };
367                 }
368
369                 // Try a big object that will require multiple write buffers.
370                 let big_writeable = TestWriteable {
371                         field1: vec![43],
372                         field2: vec![44; 4192],
373                         field3: vec![45; 4192 + 1],
374                 };
375                 check_object_read_write!(big_writeable);
376
377                 // Try a small object that fits into one write buffer.
378                 let small_writeable = TestWriteable {
379                         field1: vec![43],
380                         field2: vec![44],
381                         field3: vec![45],
382                 };
383                 check_object_read_write!(small_writeable);
384         }
385
386         fn do_chacha_stream_adapters_ser_macros() -> Result<(), DecodeError> {
387                 let writeable = TestWriteable {
388                         field1: vec![43],
389                         field2: vec![44; 4192],
390                         field3: vec![45; 4192 + 1],
391                 };
392
393                 // First, serialize the object into a TLV stream, encrypted with ChaCha20Poly1305.
394                 let rho = [42; 32];
395                 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &writeable);
396                 let mut writer = ser::VecWriter(Vec::new());
397                 encode_tlv_stream!(&mut writer, {
398                         (1, write_adapter, required),
399                 });
400
401                 // Now deserialize the object back and make sure it matches the original.
402                 let mut read_adapter: Option<ChaChaPolyReadAdapter<TestWriteable>> = None;
403                 decode_tlv_stream!(&writer.0[..], {
404                         (1, read_adapter, (option: LengthReadableArgs, rho)),
405                 });
406                 assert_eq!(writeable, read_adapter.unwrap().readable);
407
408                 Ok(())
409         }
410
411         #[test]
412         fn chacha_stream_adapters_ser_macros() {
413                 // Test that our stream adapters work as expected with the TLV macros.
414                 // This also serves to test the `option: $trait` variant of the `_decode_tlv` ser macro.
415                 do_chacha_stream_adapters_ser_macros().unwrap()
416         }
417 }