Skip to content

Commit c46327c

Browse files
committed
Add support for variable-length onion payload reads using TLV
1 parent df90668 commit c46327c

File tree

8 files changed

+184
-48
lines changed

8 files changed

+184
-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_inline(&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: 129 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};
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
@@ -611,15 +611,20 @@ mod fuzzy_internal_msgs {
611611
// them from untrusted input):
612612

613613
pub(crate) enum OnionHopDataFormat {
614-
Legacy, // aka Realm-0
614+
Legacy { // aka Realm-0
615+
short_channel_id: u64,
616+
},
617+
NonFinalNode {
618+
short_channel_id: u64,
619+
},
620+
FinalNode,
615621
}
616622

617623
pub struct OnionHopData {
618624
pub(crate) format: OnionHopDataFormat,
619-
pub(crate) short_channel_id: u64,
620625
pub(crate) amt_to_forward: u64,
621626
pub(crate) outgoing_cltv_value: u32,
622-
// 12 bytes of 0-padding
627+
// 12 bytes of 0-padding for Legacy format
623628
}
624629

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

973998
impl<R: Read> Readable<R> for OnionHopData {
974-
fn read(r: &mut R) -> Result<Self, DecodeError> {
975-
Ok(OnionHopData {
976-
format: {
977-
let r: u8 = Readable::read(r)?;
978-
if r != 0 {
979-
return Err(DecodeError::UnknownVersion);
999+
fn read(mut r: &mut R) -> Result<Self, DecodeError> {
1000+
use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1001+
let v: VarInt = Decodable::consensus_decode(&mut r)
1002+
.map_err(|e| match e {
1003+
Error::Io(ioe) => DecodeError::from(ioe),
1004+
_ => DecodeError::InvalidValue
1005+
})?;
1006+
let (format, amt, cltv_value) = if v.0 != 0 {
1007+
let mut rd = FixedLengthReader { read: r, read_len: 0, max_len: v.0 };
1008+
let mut amt: u64 = 0;
1009+
let mut cltv_value: u32 = 0;
1010+
let mut short_id: Option<u64> = None;
1011+
decode_tlv!(&mut rd, {
1012+
(2, amt),
1013+
(4, cltv_value)
1014+
}, {
1015+
(6, short_id)
1016+
});
1017+
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1018+
let format = if let Some(short_channel_id) = short_id {
1019+
OnionHopDataFormat::NonFinalNode {
1020+
short_channel_id,
9801021
}
981-
OnionHopDataFormat::Legacy
982-
},
983-
short_channel_id: Readable::read(r)?,
984-
amt_to_forward: Readable::read(r)?,
985-
outgoing_cltv_value: {
986-
let v: u32 = Readable::read(r)?;
987-
r.read_exact(&mut [0; 12])?;
988-
v
989-
},
1022+
} else {
1023+
OnionHopDataFormat::FinalNode
1024+
};
1025+
(format, amt, cltv_value)
1026+
} else {
1027+
let format = OnionHopDataFormat::Legacy {
1028+
short_channel_id: Readable::read(r)?,
1029+
};
1030+
let amt: u64 = Readable::read(r)?;
1031+
let cltv_value: u32 = Readable::read(r)?;
1032+
r.read_exact(&mut [0; 12])?;
1033+
(format, amt, cltv_value)
1034+
};
1035+
1036+
Ok(OnionHopData {
1037+
format,
1038+
amt_to_forward: amt,
1039+
outgoing_cltv_value: cltv_value,
9901040
})
9911041
}
9921042
}
@@ -1272,9 +1322,9 @@ impl_writeable_len_match!(NodeAnnouncement, {
12721322
mod tests {
12731323
use hex;
12741324
use ln::msgs;
1275-
use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket};
1325+
use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
12761326
use ln::channelmanager::{PaymentPreimage, PaymentHash};
1277-
use util::ser::Writeable;
1327+
use util::ser::{Writeable, Readable};
12781328

12791329
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
12801330
use bitcoin_hashes::hex::FromHex;
@@ -1286,6 +1336,8 @@ mod tests {
12861336
use secp256k1::key::{PublicKey,SecretKey};
12871337
use secp256k1::{Secp256k1, Message};
12881338

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

0 commit comments

Comments
 (0)