Skip to content

Commit 3f3335a

Browse files
authored
Merge pull request #1715 from TheBlueMatt/2022-09-fix-msg-send
Fix encryption of broadcasted gossip messages
2 parents dbd0ab8 + 45ec1db commit 3f3335a

File tree

4 files changed

+77
-17
lines changed

4 files changed

+77
-17
lines changed

fuzz/src/peer_crypt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ pub fn do_test(data: &[u8]) {
7474
};
7575
loop {
7676
if get_slice!(1)[0] == 0 {
77-
crypter.encrypt_message(get_slice!(slice_to_be16(get_slice!(2))));
77+
crypter.encrypt_buffer(get_slice!(slice_to_be16(get_slice!(2))));
7878
} else {
7979
let len = match crypter.decrypt_length_header(get_slice!(16+2)) {
8080
Ok(len) => len,

lightning/src/ln/peer_channel_encryptor.rs

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use prelude::*;
1111

1212
use ln::msgs::LightningError;
1313
use ln::msgs;
14+
use ln::wire;
1415

1516
use bitcoin::hashes::{Hash, HashEngine};
1617
use bitcoin::hashes::sha256::Hash as Sha256;
@@ -22,6 +23,7 @@ use bitcoin::secp256k1;
2223

2324
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;
2425
use util::crypto::hkdf_extract_expand_twice;
26+
use util::ser::VecWriter;
2527
use bitcoin::hashes::hex::ToHex;
2628

2729
/// Maximum Lightning message data length according to
@@ -142,6 +144,19 @@ impl PeerChannelEncryptor {
142144
res[plaintext.len()..].copy_from_slice(&tag);
143145
}
144146

147+
#[inline]
148+
/// Encrypts the message in res[offset..] in-place and pushes a 16-byte tag onto the end of
149+
/// res.
150+
fn encrypt_in_place_with_ad(res: &mut Vec<u8>, offset: usize, n: u64, key: &[u8; 32], h: &[u8]) {
151+
let mut nonce = [0; 12];
152+
nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
153+
154+
let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
155+
let mut tag = [0; 16];
156+
chacha.encrypt_full_message_in_place(&mut res[offset..], &mut tag);
157+
res.extend_from_slice(&tag);
158+
}
159+
145160
#[inline]
146161
fn decrypt_with_ad(res: &mut[u8], n: u64, key: &[u8; 32], h: &[u8], cyphertext: &[u8]) -> Result<(), LightningError> {
147162
let mut nonce = [0; 12];
@@ -372,9 +387,9 @@ impl PeerChannelEncryptor {
372387
Ok(self.their_node_id.unwrap().clone())
373388
}
374389

375-
/// Encrypts the given message, returning the encrypted version
390+
/// Encrypts the given pre-serialized message, returning the encrypted version.
376391
/// panics if msg.len() > 65535 or Noise handshake has not finished.
377-
pub fn encrypt_message(&mut self, msg: &[u8]) -> Vec<u8> {
392+
pub fn encrypt_buffer(&mut self, msg: &[u8]) -> Vec<u8> {
378393
if msg.len() > LN_MAX_MSG_LEN {
379394
panic!("Attempted to encrypt message longer than 65535 bytes!");
380395
}
@@ -403,6 +418,42 @@ impl PeerChannelEncryptor {
403418
res
404419
}
405420

421+
/// Encrypts the given message, returning the encrypted version.
422+
/// panics if the length of `message`, once encoded, is greater than 65535 or if the Noise
423+
/// handshake has not finished.
424+
pub fn encrypt_message<M: wire::Type>(&mut self, message: &M) -> Vec<u8> {
425+
// Allocate a buffer with 2KB, fitting most common messages. Reserve the first 16+2 bytes
426+
// for the 2-byte message type prefix and its MAC.
427+
let mut res = VecWriter(Vec::with_capacity(2048));
428+
res.0.resize(16 + 2, 0);
429+
wire::write(message, &mut res).expect("In-memory messages must never fail to serialize");
430+
431+
let msg_len = res.0.len() - 16 - 2;
432+
if msg_len > LN_MAX_MSG_LEN {
433+
panic!("Attempted to encrypt message longer than 65535 bytes!");
434+
}
435+
436+
match self.noise_state {
437+
NoiseState::Finished { ref mut sk, ref mut sn, ref mut sck, rk: _, rn: _, rck: _ } => {
438+
if *sn >= 1000 {
439+
let (new_sck, new_sk) = hkdf_extract_expand_twice(sck, sk);
440+
*sck = new_sck;
441+
*sk = new_sk;
442+
*sn = 0;
443+
}
444+
445+
Self::encrypt_with_ad(&mut res.0[0..16+2], *sn, sk, &[0; 0], &(msg_len as u16).to_be_bytes());
446+
*sn += 1;
447+
448+
Self::encrypt_in_place_with_ad(&mut res.0, 16+2, *sn, sk, &[0; 0]);
449+
*sn += 1;
450+
},
451+
_ => panic!("Tried to encrypt a message prior to noise handshake completion"),
452+
}
453+
454+
res.0
455+
}
456+
406457
/// Decrypts a message length header from the remote peer.
407458
/// panics if noise handshake has not yet finished or msg.len() != 18
408459
pub fn decrypt_length_header(&mut self, msg: &[u8]) -> Result<u16, LightningError> {
@@ -682,7 +733,7 @@ mod tests {
682733

683734
for i in 0..1005 {
684735
let msg = [0x68, 0x65, 0x6c, 0x6c, 0x6f];
685-
let res = outbound_peer.encrypt_message(&msg);
736+
let res = outbound_peer.encrypt_buffer(&msg);
686737
assert_eq!(res.len(), 5 + 2*16 + 2);
687738

688739
let len_header = res[0..2+16].to_vec();
@@ -716,7 +767,7 @@ mod tests {
716767
fn max_message_len_encryption() {
717768
let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
718769
let msg = [4u8; LN_MAX_MSG_LEN + 1];
719-
outbound_peer.encrypt_message(&msg);
770+
outbound_peer.encrypt_buffer(&msg);
720771
}
721772

722773
#[test]

lightning/src/ln/peer_handler.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -367,8 +367,10 @@ struct Peer {
367367

368368
pending_outbound_buffer: LinkedList<Vec<u8>>,
369369
pending_outbound_buffer_first_msg_offset: usize,
370-
// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily prioritize
371-
// channel messages over them.
370+
/// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
371+
/// prioritize channel messages over them.
372+
///
373+
/// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
372374
gossip_broadcast_buffer: LinkedList<Vec<u8>>,
373375
awaiting_write_event: bool,
374376

@@ -822,7 +824,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
822824
}
823825
if peer.should_buffer_gossip_broadcast() {
824826
if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
825-
peer.pending_outbound_buffer.push_back(msg);
827+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
826828
}
827829
}
828830
if peer.should_buffer_gossip_backfill() {
@@ -941,22 +943,19 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
941943

942944
/// Append a message to a peer's pending outbound/write buffer
943945
fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
944-
let mut buffer = VecWriter(Vec::with_capacity(2048));
945-
wire::write(message, &mut buffer).unwrap(); // crash if the write failed
946-
947946
if is_gossip_msg(message.type_id()) {
948947
log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
949948
} else {
950949
log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
951950
}
952951
peer.msgs_sent_since_pong += 1;
953-
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&buffer.0[..]));
952+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
954953
}
955954

956955
/// Append a message to a peer's pending outbound/write gossip broadcast buffer
957-
fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
956+
fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
958957
peer.msgs_sent_since_pong += 1;
959-
peer.gossip_broadcast_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
958+
peer.gossip_broadcast_buffer.push_back(encoded_message);
960959
}
961960

962961
fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
@@ -1438,7 +1437,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
14381437
if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
14391438
continue;
14401439
}
1441-
self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1440+
self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
14421441
}
14431442
},
14441443
wire::Message::NodeAnnouncement(ref msg) => {
@@ -1461,7 +1460,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
14611460
if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
14621461
continue;
14631462
}
1464-
self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1463+
self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
14651464
}
14661465
},
14671466
wire::Message::ChannelUpdate(ref msg) => {
@@ -1481,7 +1480,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
14811480
if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
14821481
continue;
14831482
}
1484-
self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1483+
self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
14851484
}
14861485
},
14871486
_ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),

lightning/src/util/chacha20poly1305rfc.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ mod real_chachapoly {
7474
self.mac.raw_result(out_tag);
7575
}
7676

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+
7782
// Encrypt `input_output` in-place. To finish and calculate the tag, use `finish_and_get_tag`
7883
// below.
7984
pub(super) fn encrypt_in_place(&mut self, input_output: &mut [u8]) {
@@ -284,6 +289,11 @@ mod fuzzy_chachapoly {
284289
self.finished = true;
285290
}
286291

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+
287297
pub(super) fn encrypt_in_place(&mut self, _input_output: &mut [u8]) {
288298
assert!(self.finished == false);
289299
}

0 commit comments

Comments
 (0)