Skip to content

Commit 3faea33

Browse files
Fix phantom malformed onion error packet
Ensure we fail back phantom malformed payments with an update_fail_htlc s.t. the error contains the sha256 of the onion, per LN protocol.
1 parent f1aba79 commit 3faea33

File tree

2 files changed

+118
-9
lines changed

2 files changed

+118
-9
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ mod inbound_payment {
358358
// our payment, which we can use to decode errors or inform the user that the payment was sent.
359359

360360
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
361-
enum PendingHTLCRouting {
361+
pub(super) enum PendingHTLCRouting {
362362
Forward {
363363
onion_packet: msgs::OnionPacket,
364364
short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
@@ -376,8 +376,8 @@ enum PendingHTLCRouting {
376376

377377
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
378378
pub(super) struct PendingHTLCInfo {
379-
routing: PendingHTLCRouting,
380-
incoming_shared_secret: [u8; 32],
379+
pub(super) routing: PendingHTLCRouting,
380+
pub(super) incoming_shared_secret: [u8; 32],
381381
payment_hash: PaymentHash,
382382
pub(super) amt_to_forward: u64,
383383
pub(super) outgoing_cltv_value: u32,
@@ -3043,7 +3043,12 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
30433043
let next_hop = match onion_utils::decode_next_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
30443044
Ok(res) => res,
30453045
Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3046-
fail_forward!(err_msg, err_code, Vec::new(), None);
3046+
let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
3047+
// In this scenario, the phantom would have sent us an
3048+
// `update_fail_malformed_htlc`, meaning here we encrypt the error as
3049+
// if it came from us (the second-to-last hop) but contains the sha256
3050+
// of the onion.
3051+
fail_forward!(err_msg, err_code, sha256_of_onion.to_vec(), None);
30473052
},
30483053
Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
30493054
fail_forward!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));

lightning/src/ln/onion_route_tests.rs

Lines changed: 109 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,28 @@
1212
//! returned errors decode to the correct thing.
1313
1414
use chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
15+
use chain::keysinterface::{KeysInterface, Recipient};
1516
use ln::{PaymentHash, PaymentSecret};
16-
use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY};
17+
use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
1718
use ln::onion_utils;
18-
use routing::network_graph::NetworkUpdate;
19-
use routing::router::Route;
20-
use ln::features::InitFeatures;
19+
use routing::network_graph::{NetworkUpdate, RoutingFees};
20+
use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
21+
use ln::features::{InitFeatures, InvoiceFeatures};
2122
use ln::msgs;
2223
use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
2324
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2425
use util::ser::{Writeable, Writer};
26+
use util::test_utils;
2527
use util::config::UserConfig;
2628

2729
use bitcoin::hash_types::BlockHash;
2830

2931
use bitcoin::hashes::Hash;
32+
use bitcoin::hashes::sha256::Hash as Sha256;
3033

3134
use bitcoin::secp256k1;
3235
use bitcoin::secp256k1::Secp256k1;
33-
use bitcoin::secp256k1::key::SecretKey;
36+
use bitcoin::secp256k1::key::{PublicKey, SecretKey};
3437

3538
use io;
3639
use prelude::*;
@@ -573,3 +576,104 @@ fn test_onion_failure() {
573576
nodes[2].node.fail_htlc_backwards(&payment_hash);
574577
}, true, Some(23), None, None);
575578
}
579+
580+
macro_rules! get_phantom_route {
581+
($nodes: expr, $amt: expr, $channel: expr) => {{
582+
let secp_ctx = Secp256k1::new();
583+
let phantom_secret = $nodes[1].keys_manager.get_node_secret(Recipient::PhantomNode).unwrap();
584+
let phantom_pubkey = PublicKey::from_secret_key(&secp_ctx, &phantom_secret);
585+
let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
586+
let payment_params = PaymentParameters::from_node_id(phantom_pubkey)
587+
.with_features(InvoiceFeatures::known())
588+
.with_route_hints(vec![RouteHint(vec![
589+
RouteHintHop {
590+
src_node_id: $nodes[0].node.get_our_node_id(),
591+
short_channel_id: $channel.0.contents.short_channel_id,
592+
fees: RoutingFees {
593+
base_msat: $channel.0.contents.fee_base_msat,
594+
proportional_millionths: $channel.0.contents.fee_proportional_millionths,
595+
},
596+
cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
597+
htlc_minimum_msat: None,
598+
htlc_maximum_msat: None,
599+
},
600+
RouteHintHop {
601+
src_node_id: phantom_route_hint.real_node_pubkey,
602+
short_channel_id: phantom_route_hint.phantom_scid,
603+
fees: RoutingFees {
604+
base_msat: 0,
605+
proportional_millionths: 0,
606+
},
607+
cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
608+
htlc_minimum_msat: None,
609+
htlc_maximum_msat: None,
610+
}
611+
])]);
612+
let scorer = test_utils::TestScorer::with_penalty(0);
613+
(get_route(
614+
&$nodes[0].node.get_our_node_id(), &payment_params, $nodes[0].network_graph,
615+
Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
616+
$amt, TEST_FINAL_CLTV, $nodes[0].logger, &scorer
617+
).unwrap(), phantom_route_hint.phantom_scid)
618+
}
619+
}}
620+
621+
#[test]
622+
fn test_phantom_onion_hmac_failure() {
623+
let chanmon_cfgs = create_chanmon_cfgs(2);
624+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627+
628+
let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
629+
630+
// Get the route.
631+
let recv_value_msat = 10_000;
632+
let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
633+
let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
634+
635+
// Route the HTLC through to the destination.
636+
nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
637+
check_added_monitors!(nodes[0], 1);
638+
let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
639+
let mut update_add = update_0.update_add_htlcs[0].clone();
640+
641+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
642+
commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
643+
644+
// Modify the payload so the phantom hop's HMAC is bogus.
645+
let sha256_of_onion = {
646+
let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
647+
let mut pending_forward = channel_state.forward_htlcs.get_mut(&phantom_scid).unwrap();
648+
match pending_forward[0] {
649+
HTLCForwardInfo::AddHTLC {
650+
forward_info: PendingHTLCInfo {
651+
routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
652+
..
653+
}, ..
654+
} => {
655+
onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
656+
Sha256::hash(&onion_packet.hop_data).into_inner().to_vec()
657+
},
658+
_ => panic!("Unexpected forward"),
659+
}
660+
};
661+
expect_pending_htlcs_forwardable_ignore!(nodes[1]);
662+
nodes[1].node.process_pending_htlc_forwards();
663+
expect_pending_htlcs_forwardable_ignore!(nodes[1]);
664+
nodes[1].node.process_pending_htlc_forwards();
665+
let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
666+
check_added_monitors!(&nodes[1], 1);
667+
assert!(update_1.update_fail_htlcs.len() == 1);
668+
let fail_msg = update_1.update_fail_htlcs[0].clone();
669+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
670+
commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
671+
672+
// Ensure the payment fails with the expected error.
673+
let mut fail_conditions = PaymentFailedConditions::new()
674+
.blamed_scid(phantom_scid)
675+
.blamed_chan_closed(true)
676+
.expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
677+
expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
678+
}
679+

0 commit comments

Comments
 (0)