Skip to content

Commit 54cab8f

Browse files
committed
Add support for variable-length onion payload reads using TLV
1 parent ccab79f commit 54cab8f

File tree

8 files changed

+185
-48
lines changed

8 files changed

+185
-48
lines changed

fuzz/src/msg_targets/gen_target.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ GEN_TEST NodeAnnouncement test_msg_exact ""
3434

3535
GEN_TEST UpdateAddHTLC test_msg_hole ", 85, 33"
3636
GEN_TEST ErrorMessage test_msg_hole ", 32, 2"
37-
GEN_TEST OnionHopData test_msg_hole ", 1+8+8+4, 12"
3837

3938
GEN_TEST Init test_msg_simple ""
39+
GEN_TEST OnionHopData test_msg_simple ""
4040
GEN_TEST Ping test_msg_simple ""
4141
GEN_TEST Pong test_msg_simple ""

fuzz/src/msg_targets/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pub mod msg_channel_update;
2020
pub mod msg_node_announcement;
2121
pub mod msg_update_add_htlc;
2222
pub mod msg_error_message;
23-
pub mod msg_onion_hop_data;
2423
pub mod msg_init;
24+
pub mod msg_onion_hop_data;
2525
pub mod msg_ping;
2626
pub mod msg_pong;

fuzz/src/msg_targets/msg_onion_hop_data.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use msg_targets::utils::VecWriter;
77

88
#[inline]
99
pub fn do_test(data: &[u8]) {
10-
test_msg_hole!(msgs::OnionHopData, data, 1+8+8+4, 12);
10+
test_msg_simple!(msgs::OnionHopData, data);
1111
}
1212

1313
#[no_mangle]

lightning/src/ln/channelmanager.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -910,14 +910,17 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
910910
Err(err) => {
911911
let error_code = match err {
912912
msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
913+
msgs::DecodeError::UnknownRequiredFeature|
914+
msgs::DecodeError::InvalidValue|
915+
msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
913916
_ => 0x2000 | 2, // Should never happen
914917
};
915918
return_err!("Unable to decode our hop data", error_code, &[0;0]);
916919
},
917920
Ok(msg) => {
918921
let mut hmac = [0; 32];
919922
if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
920-
return_err!("Unable to decode hop data", 0x4000 | 1, &[0;0]);
923+
return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
921924
}
922925
(msg, hmac)
923926
},
@@ -971,6 +974,15 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
971974
} else {
972975
let mut new_packet_data = [0; 20*65];
973976
let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
977+
#[cfg(debug_assertions)]
978+
{
979+
// Check two things:
980+
// a) that the behavior of our stream here will return Ok(0) even if the TLV
981+
// read above emptied out our buffer and the unwrap() wont needlessly panic
982+
// b) that we didn't somehow magically end up with extra data.
983+
let mut t = [0; 1];
984+
debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
985+
}
974986
// Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
975987
// fill the onion hop data we'll forward to our next-hop peer.
976988
chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
@@ -995,10 +1007,18 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
9951007
hmac: next_hop_hmac.clone(),
9961008
};
9971009

1010+
let short_channel_id = match next_hop_data.format {
1011+
msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1012+
msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1013+
msgs::OnionHopDataFormat::FinalNode => {
1014+
return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1015+
},
1016+
};
1017+
9981018
PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
9991019
onion_packet: Some(outgoing_packet),
10001020
payment_hash: msg.payment_hash.clone(),
1001-
short_channel_id: next_hop_data.short_channel_id,
1021+
short_channel_id: short_channel_id,
10021022
incoming_shared_secret: shared_secret,
10031023
amt_to_forward: next_hop_data.amt_to_forward,
10041024
outgoing_cltv_value: next_hop_data.outgoing_cltv_value,

lightning/src/ln/features.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,13 +182,21 @@ impl<T: sealed::Context> Features<T> {
182182

183183
pub(crate) fn requires_unknown_bits(&self) -> bool {
184184
self.flags.iter().enumerate().any(|(idx, &byte)| {
185-
( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
185+
(match idx {
186+
0 => (byte & 0b00010100),
187+
1 => (byte & 0b01010100),
188+
_ => (byte & 0b01010101),
189+
}) != 0
186190
})
187191
}
188192

189193
pub(crate) fn supports_unknown_bits(&self) -> bool {
190194
self.flags.iter().enumerate().any(|(idx, &byte)| {
191-
( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
195+
(match idx {
196+
0 => (byte & 0b11000100),
197+
1 => (byte & 0b11111100),
198+
_ => byte,
199+
}) != 0
192200
})
193201
}
194202

lightning/src/ln/functional_tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5023,7 +5023,7 @@ fn test_onion_failure() {
50235023
// describing a length-1 TLV payload, which is obviously bogus.
50245024
new_payloads[0].data[0] = 1;
50255025
msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5026-
}, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
5026+
}, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
50275027

50285028
// final node failure
50295029
run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
@@ -5039,7 +5039,7 @@ fn test_onion_failure() {
50395039
// length-1 TLV payload, which is obviously bogus.
50405040
new_payloads[1].data[0] = 1;
50415041
msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5042-
}, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5042+
}, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
50435043

50445044
// the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
50455045
// receiving simulated fail messages

lightning/src/ln/msgs.rs

Lines changed: 130 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use std::io::Read;
2929
use std::result::Result;
3030

3131
use util::events;
32-
use util::ser::{Readable, Writeable, Writer};
32+
use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt};
3333

3434
use ln::channelmanager::{PaymentPreimage, PaymentHash};
3535

@@ -39,7 +39,7 @@ pub enum DecodeError {
3939
/// A version byte specified something we don't know how to handle.
4040
/// Includes unknown realm byte in an OnionHopData packet
4141
UnknownVersion,
42-
/// Unknown feature mandating we fail to parse message
42+
/// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type)
4343
UnknownRequiredFeature,
4444
/// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
4545
/// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
@@ -613,15 +613,20 @@ mod fuzzy_internal_msgs {
613613
// them from untrusted input):
614614

615615
pub(crate) enum OnionHopDataFormat {
616-
Legacy, // aka Realm-0
616+
Legacy { // aka Realm-0
617+
short_channel_id: u64,
618+
},
619+
NonFinalNode {
620+
short_channel_id: u64,
621+
},
622+
FinalNode,
617623
}
618624

619625
pub struct OnionHopData {
620626
pub(crate) format: OnionHopDataFormat,
621-
pub(crate) short_channel_id: u64,
622627
pub(crate) amt_to_forward: u64,
623628
pub(crate) outgoing_cltv_value: u32,
624-
// 12 bytes of 0-padding
629+
// 12 bytes of 0-padding for Legacy format
625630
}
626631

627632
pub struct DecodedOnionErrorPacket {
@@ -962,33 +967,79 @@ impl Writeable for OnionHopData {
962967
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
963968
w.size_hint(33);
964969
match self.format {
965-
OnionHopDataFormat::Legacy => 0u8.write(w)?,
970+
OnionHopDataFormat::Legacy { short_channel_id } => {
971+
0u8.write(w)?;
972+
short_channel_id.write(w)?;
973+
self.amt_to_forward.write(w)?;
974+
self.outgoing_cltv_value.write(w)?;
975+
},
976+
OnionHopDataFormat::NonFinalNode { short_channel_id } => {
977+
encode_varint_length_prefixed_tlv!(w, {
978+
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
979+
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
980+
(6, short_channel_id)
981+
});
982+
},
983+
OnionHopDataFormat::FinalNode => {
984+
encode_varint_length_prefixed_tlv!(w, {
985+
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
986+
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
987+
});
988+
},
989+
}
990+
match self.format {
991+
OnionHopDataFormat::Legacy { .. } => {
992+
w.write_all(&[0;12])?;
993+
},
994+
_ => {},
966995
}
967-
self.short_channel_id.write(w)?;
968-
self.amt_to_forward.write(w)?;
969-
self.outgoing_cltv_value.write(w)?;
970-
w.write_all(&[0;12])?;
971996
Ok(())
972997
}
973998
}
974999

9751000
impl<R: Read> Readable<R> for OnionHopData {
976-
fn read(r: &mut R) -> Result<Self, DecodeError> {
977-
Ok(OnionHopData {
978-
format: {
979-
let r: u8 = Readable::read(r)?;
980-
if r != 0 {
981-
return Err(DecodeError::UnknownVersion);
1001+
fn read(mut r: &mut R) -> Result<Self, DecodeError> {
1002+
use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1003+
let v: VarInt = Decodable::consensus_decode(&mut r)
1004+
.map_err(|e| match e {
1005+
Error::Io(ioe) => DecodeError::from(ioe),
1006+
_ => DecodeError::InvalidValue
1007+
})?;
1008+
const LEGACY_ONION_HOP_FLAG: u64 = 0;
1009+
let (format, amt, cltv_value) = if v.0 != LEGACY_ONION_HOP_FLAG {
1010+
let mut rd = FixedLengthReader::new(r, v.0);
1011+
let mut amt = HighZeroBytesDroppedVarInt(0u64);
1012+
let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
1013+
let mut short_id: Option<u64> = None;
1014+
decode_tlv!(&mut rd, {
1015+
(2, amt),
1016+
(4, cltv_value)
1017+
}, {
1018+
(6, short_id)
1019+
});
1020+
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1021+
let format = if let Some(short_channel_id) = short_id {
1022+
OnionHopDataFormat::NonFinalNode {
1023+
short_channel_id,
9821024
}
983-
OnionHopDataFormat::Legacy
984-
},
985-
short_channel_id: Readable::read(r)?,
986-
amt_to_forward: Readable::read(r)?,
987-
outgoing_cltv_value: {
988-
let v: u32 = Readable::read(r)?;
989-
r.read_exact(&mut [0; 12])?;
990-
v
991-
},
1025+
} else {
1026+
OnionHopDataFormat::FinalNode
1027+
};
1028+
(format, amt.0, cltv_value.0)
1029+
} else {
1030+
let format = OnionHopDataFormat::Legacy {
1031+
short_channel_id: Readable::read(r)?,
1032+
};
1033+
let amt: u64 = Readable::read(r)?;
1034+
let cltv_value: u32 = Readable::read(r)?;
1035+
r.read_exact(&mut [0; 12])?;
1036+
(format, amt, cltv_value)
1037+
};
1038+
1039+
Ok(OnionHopData {
1040+
format,
1041+
amt_to_forward: amt,
1042+
outgoing_cltv_value: cltv_value,
9921043
})
9931044
}
9941045
}
@@ -1274,9 +1325,9 @@ impl_writeable_len_match!(NodeAnnouncement, {
12741325
mod tests {
12751326
use hex;
12761327
use ln::msgs;
1277-
use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket};
1328+
use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
12781329
use ln::channelmanager::{PaymentPreimage, PaymentHash};
1279-
use util::ser::Writeable;
1330+
use util::ser::{Writeable, Readable};
12801331

12811332
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
12821333
use bitcoin_hashes::hex::FromHex;
@@ -1288,6 +1339,8 @@ mod tests {
12881339
use secp256k1::key::{PublicKey,SecretKey};
12891340
use secp256k1::{Secp256k1, Message};
12901341

1342+
use std::io::Cursor;
1343+
12911344
#[test]
12921345
fn encoding_channel_reestablish_no_secret() {
12931346
let cr = msgs::ChannelReestablish {
@@ -1927,4 +1980,54 @@ mod tests {
19271980
let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
19281981
assert_eq!(encoded_value, target_value);
19291982
}
1983+
1984+
#[test]
1985+
fn encoding_legacy_onion_hop_data() {
1986+
let msg = msgs::OnionHopData {
1987+
format: OnionHopDataFormat::Legacy {
1988+
short_channel_id: 0xdeadbeef1bad1dea,
1989+
},
1990+
amt_to_forward: 0x0badf00d01020304,
1991+
outgoing_cltv_value: 0xffffffff,
1992+
};
1993+
let encoded_value = msg.encode();
1994+
let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
1995+
assert_eq!(encoded_value, target_value);
1996+
}
1997+
1998+
#[test]
1999+
fn encoding_nonfinal_onion_hop_data() {
2000+
let mut msg = msgs::OnionHopData {
2001+
format: OnionHopDataFormat::NonFinalNode {
2002+
short_channel_id: 0xdeadbeef1bad1dea,
2003+
},
2004+
amt_to_forward: 0x0badf00d01020304,
2005+
outgoing_cltv_value: 0xffffffff,
2006+
};
2007+
let encoded_value = msg.encode();
2008+
let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2009+
assert_eq!(encoded_value, target_value);
2010+
msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2011+
if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2012+
assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2013+
} else { panic!(); }
2014+
assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2015+
assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2016+
}
2017+
2018+
#[test]
2019+
fn encoding_final_onion_hop_data() {
2020+
let mut msg = msgs::OnionHopData {
2021+
format: OnionHopDataFormat::FinalNode,
2022+
amt_to_forward: 0x0badf00d01020304,
2023+
outgoing_cltv_value: 0xffffffff,
2024+
};
2025+
let encoded_value = msg.encode();
2026+
let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2027+
assert_eq!(encoded_value, target_value);
2028+
msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2029+
if let OnionHopDataFormat::FinalNode = msg.format { } else { panic!(); }
2030+
assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2031+
assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2032+
}
19302033
}

0 commit comments

Comments
 (0)