Skip to content

Authenticate blinded path contexts with a secret AAD in the MAC #3845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/blinded_path/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ impl BlindedMessagePath {
recipient_node_id,
context,
&blinding_secret,
[41; 32], // TODO: Pass this in
)
.map_err(|_| ())?,
}))
Expand Down Expand Up @@ -514,6 +515,7 @@ pub(crate) const MESSAGE_PADDING_ROUND_OFF: usize = 100;
pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
secp_ctx: &Secp256k1<T>, intermediate_nodes: &[MessageForwardNode],
recipient_node_id: PublicKey, context: MessageContext, session_priv: &SecretKey,
local_node_receive_key: [u8; 32],
) -> Result<Vec<BlindedHop>, secp256k1::Error> {
let pks = intermediate_nodes
.iter()
Expand All @@ -536,13 +538,13 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(

if is_compact {
let path = pks.zip(tlvs);
utils::construct_blinded_hops(secp_ctx, path, session_priv)
utils::construct_blinded_hops(secp_ctx, path, session_priv, Some(local_node_receive_key))
} else {
let path =
pks.zip(tlvs.map(|tlv| BlindedPathWithPadding {
tlvs: tlv,
round_off: MESSAGE_PADDING_ROUND_OFF,
}));
utils::construct_blinded_hops(secp_ctx, path, session_priv)
utils::construct_blinded_hops(secp_ctx, path, session_priv, Some(local_node_receive_key))
}
}
2 changes: 1 addition & 1 deletion lightning/src/blinded_path/payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
tlvs.map(|tlv| BlindedPathWithPadding { tlvs: tlv, round_off: PAYMENT_PADDING_ROUND_OFF }),
);

utils::construct_blinded_hops(secp_ctx, path, session_priv)
utils::construct_blinded_hops(secp_ctx, path, session_priv, None)
}

/// `None` if underflow occurs.
Expand Down
57 changes: 37 additions & 20 deletions lightning/src/blinded_path/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};

use super::message::BlindedMessagePath;
use super::{BlindedHop, BlindedPath};
use crate::crypto::streams::ChaChaPolyWriteAdapter;
use crate::crypto::chacha20poly1305rfc::ChaCha20Poly1305RFC;
use crate::crypto::streams::chachapoly_encrypt_with_swapped_aad;
use crate::io;
use crate::ln::onion_utils;
use crate::onion_message::messenger::Destination;
Expand All @@ -38,7 +39,7 @@ macro_rules! build_keys_helper {
let mut onion_packet_pubkey = msg_blinding_point.clone();

macro_rules! build_keys {
($hop: expr, $blinded: expr, $encrypted_payload: expr) => {{
($hop: expr, $blinded: expr, $encrypted_payload: expr, $node_recv_key: expr) => {{
let pk = *$hop.borrow();
let encrypted_data_ss = SharedSecret::new(&pk, &msg_blinding_point_priv);

Expand All @@ -65,16 +66,17 @@ macro_rules! build_keys_helper {
onion_packet_pubkey,
rho,
unblinded_hop_opt,
$node_recv_key,
$encrypted_payload,
);
(encrypted_data_ss, onion_packet_ss)
}};
}

macro_rules! build_keys_in_loop {
($pk: expr, $blinded: expr, $encrypted_payload: expr) => {
($pk: expr, $blinded: expr, $encrypted_payload: expr, $node_recv_key: expr) => {
let (encrypted_data_ss, onion_packet_ss) =
build_keys!($pk, $blinded, $encrypted_payload);
build_keys!($pk, $blinded, $encrypted_payload, $node_recv_key);

let msg_blinding_point_blinding_factor = {
let mut sha = Sha256::engine();
Expand Down Expand Up @@ -105,48 +107,52 @@ macro_rules! build_keys_helper {
};
}

#[inline]
pub(crate) fn construct_keys_for_onion_message<'a, T, I, F>(
secp_ctx: &Secp256k1<T>, unblinded_path: I, destination: Destination, session_priv: &SecretKey,
mut callback: F,
) -> Result<(), secp256k1::Error>
where
T: secp256k1::Signing + secp256k1::Verification,
I: Iterator<Item = PublicKey>,
F: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<PublicKey>, Option<Vec<u8>>),
F: FnMut(SharedSecret, PublicKey, [u8; 32], Option<PublicKey>, Option<Vec<u8>>),
{
build_keys_helper!(session_priv, secp_ctx, callback);
let mut callback_wrapper = |_, ss, pk, encrypted_payload_rho, unblinded_hop_data, _: Option<()>, encrypted_payload| {
callback(ss, pk, encrypted_payload_rho, unblinded_hop_data, encrypted_payload);
};
build_keys_helper!(session_priv, secp_ctx, callback_wrapper);

for pk in unblinded_path {
build_keys_in_loop!(pk, false, None);
build_keys_in_loop!(pk, false, None, None);
}
match destination {
Destination::Node(pk) => {
build_keys!(pk, false, None);
build_keys!(pk, false, None, None);
},
Destination::BlindedPath(BlindedMessagePath(BlindedPath { blinded_hops, .. })) => {
for hop in blinded_hops {
build_keys_in_loop!(hop.blinded_node_id, true, Some(hop.encrypted_payload));
build_keys_in_loop!(hop.blinded_node_id, true, Some(hop.encrypted_payload), None);
}
},
}
Ok(())
}

#[inline]
pub(super) fn construct_keys_for_blinded_path<'a, T, I, F, H>(
secp_ctx: &Secp256k1<T>, unblinded_path: I, session_priv: &SecretKey, mut callback: F,
fn construct_keys_for_blinded_path<'a, T, I, F, H>(
secp_ctx: &Secp256k1<T>, unblinded_path: I, session_priv: &SecretKey,
mut last_hop_receive_key: Option<[u8; 32]>, mut callback: F,
) -> Result<(), secp256k1::Error>
where
T: secp256k1::Signing + secp256k1::Verification,
H: Borrow<PublicKey>,
I: Iterator<Item = H>,
F: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<H>, Option<Vec<u8>>),
F: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<H>, Option<[u8; 32]>, Option<Vec<u8>>),
{
build_keys_helper!(session_priv, secp_ctx, callback);

for pk in unblinded_path {
build_keys_in_loop!(pk, false, None);
let mut iter = unblinded_path.peekable();
while let Some(pk) = iter.next() {
let receive_key = if iter.peek().is_none() { last_hop_receive_key.take() } else { None };
build_keys_in_loop!(pk, false, None, receive_key);
}
Ok(())
}
Expand All @@ -164,6 +170,7 @@ impl<W: Writeable> Borrow<PublicKey> for PublicKeyWithTlvs<W> {

pub(crate) fn construct_blinded_hops<'a, T, I, W>(
secp_ctx: &Secp256k1<T>, unblinded_path: I, session_priv: &SecretKey,
last_hop_receive_key: Option<[u8; 32]>,
) -> Result<Vec<BlindedHop>, secp256k1::Error>
where
T: secp256k1::Signing + secp256k1::Verification,
Expand All @@ -175,12 +182,14 @@ where
secp_ctx,
unblinded_path.map(|(pubkey, tlvs)| PublicKeyWithTlvs { pubkey, tlvs }),
session_priv,
|blinded_node_id, _, _, encrypted_payload_rho, unblinded_hop_data, _| {
last_hop_receive_key,
|blinded_node_id, _, _, encrypted_payload_rho, unblinded_hop_data, hop_recv_key, _| {
blinded_hops.push(BlindedHop {
blinded_node_id,
encrypted_payload: encrypt_payload(
unblinded_hop_data.unwrap().tlvs,
encrypted_payload_rho,
hop_recv_key,
),
});
},
Expand All @@ -189,9 +198,17 @@ where
}

/// Encrypt TLV payload to be used as a [`crate::blinded_path::BlindedHop::encrypted_payload`].
fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_rho: [u8; 32]) -> Vec<u8> {
let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_rho, &payload);
write_adapter.encode()
fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_rho: [u8; 32], hop_recv_key: Option<[u8; 32]>) -> Vec<u8> {
let mut payload_data = payload.encode();
if let Some(hop_recv_key) = hop_recv_key {
chachapoly_encrypt_with_swapped_aad(payload_data, encrypted_tlvs_rho, hop_recv_key)
} else {
let mut chacha = ChaCha20Poly1305RFC::new(&encrypted_tlvs_rho, &[0; 12], &[]);
let mut tag = [0; 16];
chacha.encrypt_full_message_in_place(&mut payload_data, &mut tag);
payload_data.extend_from_slice(&tag);
payload_data
}
}

/// A data structure used exclusively to pad blinded path payloads, ensuring they are of
Expand Down
10 changes: 4 additions & 6 deletions lightning/src/crypto/chacha20poly1305rfc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ mod real_chachapoly {
self.finished = true;
self.mac.input(&self.aad_len.to_le_bytes());
self.mac.input(&(self.data_len as u64).to_le_bytes());
self.mac.raw_result(out_tag);
out_tag.copy_from_slice(&self.mac.result());
}

pub fn encrypt_full_message_in_place(
Expand All @@ -94,7 +94,7 @@ mod real_chachapoly {
self.finished = true;
self.mac.input(&self.aad_len.to_le_bytes());
self.mac.input(&(self.data_len as u64).to_le_bytes());
self.mac.raw_result(out_tag);
out_tag.copy_from_slice(&self.mac.result());
}

/// Decrypt the `input`, checking the given `tag` prior to writing the decrypted contents
Expand All @@ -115,8 +115,7 @@ mod real_chachapoly {
self.mac.input(&self.aad_len.to_le_bytes());
self.mac.input(&(self.data_len as u64).to_le_bytes());

let mut calc_tag = [0u8; 16];
self.mac.raw_result(&mut calc_tag);
let calc_tag = self.mac.result();
if fixed_time_eq(&calc_tag, tag) {
self.cipher.process(input, output);
Ok(())
Expand Down Expand Up @@ -156,8 +155,7 @@ mod real_chachapoly {
self.mac.input(&self.aad_len.to_le_bytes());
self.mac.input(&(self.data_len as u64).to_le_bytes());

let mut calc_tag = [0u8; 16];
self.mac.raw_result(&mut calc_tag);
let calc_tag = self.mac.result();
if fixed_time_eq(&calc_tag, tag) {
true
} else {
Expand Down
13 changes: 7 additions & 6 deletions lightning/src/crypto/poly1305.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,16 @@ impl Poly1305 {
self.leftover = m.len();
}

pub fn raw_result(&mut self, output: &mut [u8]) {
assert!(output.len() >= 16);
pub fn result(&mut self) -> [u8; 16] {
if !self.finalized {
self.finish();
}
let mut output = [0; 16];
output[0..4].copy_from_slice(&self.h[0].to_le_bytes());
output[4..8].copy_from_slice(&self.h[1].to_le_bytes());
output[8..12].copy_from_slice(&self.h[2].to_le_bytes());
output[12..16].copy_from_slice(&self.h[3].to_le_bytes());
output
}
}

Expand All @@ -270,10 +271,10 @@ mod test {

use super::Poly1305;

fn poly1305(key: &[u8], msg: &[u8], mac: &mut [u8]) {
fn poly1305(key: &[u8], msg: &[u8], mac: &mut [u8; 16]) {
let mut poly = Poly1305::new(key);
poly.input(msg);
poly.raw_result(mac);
*mac = poly.result();
}

#[test]
Expand Down Expand Up @@ -318,7 +319,7 @@ mod test {
poly.input(&msg[128..129]);
poly.input(&msg[129..130]);
poly.input(&msg[130..131]);
poly.raw_result(&mut mac);
let mac = poly.result();
assert_eq!(&mac[..], &expected[..]);
}

Expand Down Expand Up @@ -363,7 +364,7 @@ mod test {
poly1305(&key[..], &msg[0..i], &mut mac);
tpoly.input(&mac);
}
tpoly.raw_result(&mut mac);
let mac = tpoly.result();
assert_eq!(&mac[..], &total_mac[..]);
}

Expand Down
Loading
Loading