Skip to content

Commit 45ec1db

Browse files
committed
Encrypt+MAC most P2P messages in-place
For non-gossip-broadcast messages, our current flow is to first serialize the message into a `Vec`, and then allocate a new `Vec` into which we write the encrypted+MAC'd message and header. This is somewhat wasteful, and its rather simple to instead allocate only one buffer and encrypt the message in-place.
1 parent 8ec92f5 commit 45ec1db

File tree

4 files changed

+68
-10
lines changed

4 files changed

+68
-10
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: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
824824
}
825825
if peer.should_buffer_gossip_broadcast() {
826826
if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
827-
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&msg[..]));
827+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
828828
}
829829
}
830830
if peer.should_buffer_gossip_backfill() {
@@ -943,16 +943,13 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
943943

944944
/// Append a message to a peer's pending outbound/write buffer
945945
fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
946-
let mut buffer = VecWriter(Vec::with_capacity(2048));
947-
wire::write(message, &mut buffer).unwrap(); // crash if the write failed
948-
949946
if is_gossip_msg(message.type_id()) {
950947
log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
951948
} else {
952949
log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
953950
}
954951
peer.msgs_sent_since_pong += 1;
955-
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));
956953
}
957954

958955
/// Append a message to a peer's pending outbound/write gossip broadcast buffer

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)