Skip to content
Open
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
10 changes: 10 additions & 0 deletions src/Rpc/NodeGuardService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,16 @@ public override async Task<AddNodeResponse> AddNode(AddNodeRequest request, Serv
RefuseSparkWallet(await _walletRepository.GetById(request.ReturningFundsWalletId));
}

// A managed node is only added when the LND at its endpoint holds its key
if (!string.IsNullOrWhiteSpace(node.Endpoint) && !string.IsNullOrWhiteSpace(node.ChannelAdminMacaroon))
{
var identityError = await _lightningService.GetNodeIdentityError(node);
if (identityError != null)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition, identityError));
}
}

try
{
var result = await _nodeRepository.AddAsync(node);
Expand Down
36 changes: 36 additions & 0 deletions src/Services/LightningService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@ public interface ILightningService
/// <returns></returns>
public Task<uint?> GetBlockHeight(Node node);

/// <summary>
/// Checks that the LND behind the node's endpoint and macaroon is the node itself: its identity pubkey is the
/// node's. Returns null when it is, and otherwise why it could not be confirmed (a different pubkey, or the
/// LND could not be asked).
/// </summary>
public Task<string?> GetNodeIdentityError(Node node);

/// <summary>
/// Lists all channels for a given node
/// </summary>
Expand Down Expand Up @@ -361,6 +368,17 @@ public async Task OpenChannel(ChannelOperationRequest channelOperationRequest)
source.Name,
destination.Name);

// A node's endpoint and macaroon can be edited, so the LND they lead to is asked who it is before the
// wallet funds a channel on it: otherwise the funds would open a channel on whatever node answers
var identityError = await GetNodeIdentityError(source);
if (identityError != null)
{
_logger.LogError(
"Channel open request {RequestId} refused, the source node could not be confirmed: {Reason}",
channelOperationRequest.Id, identityError);
throw new InvalidOperationException(identityError);
}

var combinedPSBT = GetCombinedPsbt(channelOperationRequest, _logger);


Expand Down Expand Up @@ -1618,6 +1636,24 @@ public async Task<Dictionary<ulong, ChannelState>> GetChannelsState()
return info?.BlockHeight;
}

public async Task<string?> GetNodeIdentityError(Node node)
{
if (node == null) throw new ArgumentNullException(nameof(node));

var info = await _lightningClientService.GetInfo(node);
if (info == null)
{
return $"The LND at {node.Endpoint} could not be asked for its identity, so it cannot be confirmed to be node {node.Name}";
}

if (!string.Equals(info.IdentityPubkey, node.PubKey, StringComparison.OrdinalIgnoreCase))
{
Comment on lines +1643 to +1650

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM · authn — Node identity check trusts the endpoint's self-asserted pubkey

GetInfo returns whatever IdentityPubkey the answering server claims; it is not a proof of key. An attacker who sets a node's Endpoint and ChannelAdminMacaroon (a NodeManager/Superadmin editing the node in Nodes.razor, which permits both) points the node at a modified LND or fake gRPC server that answers GetInfo with the node's real pubkey — public information advertised on the Lightning network — and accepts the configured macaroon. GetNodeIdentityError returns null, so OpenChannel proceeds: the wallet's PSBT funds a 2-of-2 channel whose entire local balance sits on the attacker's LND and is spendable by them. Multisig signers approving the request see only the node name, not the endpoint, so the switch is invisible to them. TLS does not help: CreateLightningClient accepts any server certificate (LightningClientService.cs:71), so a network-position attacker can spoof the same exchange. A real binding would require SignMessage/VerifyMessage with the node key or pinning the LND TLS cert.

Threat: a NodeGuard user with node-edit rights (NodeManager role) running their own gRPC endpoint, or a network attacker between NodeGuard and the node, starting from an authenticated NodeGuard session with the NodeManager role (can edit a node's endpoint and channel admin macaroon), or a network position on the path to the endpoint → the check passes for an attacker-controlled LND, so an approved channel open funds a channel whose balance the attacker controls — the exact fund misdirection this PR's check claims to prevent

Checks

Ruled out: Checked GetInfo (LightningClientService.cs:143): response is self-asserted, only the macaroon authenticates. Checked TLS: DangerousAcceptAnyServerCertificateValidator (line 71, pre-existing) means the connection does not authenticate the LND either. Grepped for SignMessage/VerifyMessage: only proto definitions, no proof-of-key anywhere. Checked OpenChannel reuses the same source object/endpoint after the check, so no TOCTOU — the spoof is at the check itself.

Verified: Confirmed end to end. GetNodeIdentityError (src/Services/LightningService.cs:1639-1658) trusts GetInfo's self-asserted IdentityPubkey; no proof-of-key (SignMessage/VerifyMessage) exists outside proto stubs. Nodes.razor:72,91 lets a NodeManager edit both Endpoint and ChannelAdminMacaroon, and the open flow (LightningService.cs:373) gates wallet funding on this check before OpenChannel on the same endpoint — a NodeManager pointing the node at a rogue LND that echoes the public pubkey passes the check and receives the channel's local balance. TLS is no barrier: DangerousAcceptAnyServerCertificateValidator (LightningClientService.cs:71) also enables a network-position spoof. The check is introduced by this PR and its comment explicitly claims to mitigate edited endpoints, so it is not pre-existing or out of scope.

🤖 automated review — reply not-an-issue to dismiss

return $"The LND at {node.Endpoint} is {info.IdentityPubkey}, not node {node.Name} ({node.PubKey})";
}

return null;
}

public async Task<ListChannelsResponse?> ListChannels(Node node)
{
if (node == null) throw new ArgumentNullException(nameof(node));
Expand Down
21 changes: 19 additions & 2 deletions src/Shared/ConfirmationModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@
<CloseButton />
</ModalHeader>
<ModalBody>
@((MarkupString)Body)
@* Both are HTML-encoded by Blazor: a body never renders as raw markup *@
@if (ChildContent is not null)
{
@ChildContent
}
else
{
@Body
}
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary" Clicked="@OnCancel">@CancelLabel</Button>
Expand All @@ -22,9 +30,18 @@
[Parameter, EditorRequired]
public string Title { get; set; } = "";

[Parameter, EditorRequired]
/// <summary>
/// The message as plain text. Use <see cref="ChildContent"/> for one that needs formatting
/// </summary>
[Parameter]
public string Body { get; set; } = "";

/// <summary>
/// A formatted message, shown instead of <see cref="Body"/>
/// </summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }

[Parameter]
public string CancelLabel { get; set; } = "Cancel";

Expand Down
172 changes: 113 additions & 59 deletions src/Shared/NewSwapModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,79 @@
<ConfirmationModal
@ref="_confirmationModal"
Title="Are you sure?"
Body="@_confirmationModalBody"
OkLabel="Yes, I am sure"
OnCancel="@CloseConfirmationModal"
OnSubmit="@OnCreateSwap"/>
OnSubmit="@OnCreateSwap">
@* Written as markup, never as an HTML string: the names and the provider's error are HTML-encoded *@
@if (_confirmation is { } confirmation)
{
@if (confirmation.QuoteError is not null)
{
@:Quote was not successful because of the following error: <br><br>
<span style="color: red;">@confirmation.QuoteError</span><br><br>
@:The swap will be created with the following details:<br><br>
}
else
{
@:You are about to create a new swap with the following details:<br><br>
}

<strong>- Provider: </strong>@confirmation.Provider<br>
<strong>- Direction: </strong>@confirmation.Direction<br>
<strong>- Amount: </strong>@confirmation.Amount<br>
<strong>- Origin Node: </strong>@confirmation.NodeName<br>
<strong>- Destination Wallet: </strong>@confirmation.WalletName<br><br>

@if (confirmation.QuoteError is not null)
{
<span style="color: orange">The fees could not be estimated. Default values will be used.</span><br><br>
<br>
}
else if (confirmation.Quote is { } quote)
{
<strong>- Estimated Fees:</strong><br>
<ul>
<li><strong>Service Fee: </strong>@quote.ServiceFee</li>
@if (quote.SelectedServiceFee is not null)
{
<li style="list-style-type: none;"><span style="color: orange;"> (You selected: @quote.SelectedServiceFee, it might not go through)</span></li>
}
<li><strong>Off-Chain Fee: </strong>@quote.OffChainFee</li>
@if (quote.SelectedRoutingFee is not null)
{
<li style="list-style-type: none;"><span style="color: orange;"> (You selected: @quote.SelectedRoutingFee, it might not go through)</span></li>
}
<li><strong>On-Chain Fee: </strong>@quote.OnChainFee</li>
<li><strong>Total: </strong>@quote.TotalFees</li>
</ul>
<br>
<strong>- Estimated total cost: </strong>@quote.TotalCost<br>
@if (!quote.CouldEstimateRoutingFees)
{
<br><span style="color: orange;"><strong>Warning: </strong>Routing fees could not be estimated. The actual fees will be higher than 0.</span><br><br>
}
<br>
}
else if (confirmation.Spark is { } spark)
{
<strong>- Maximum fees:</strong><br>
<ul>
<li><strong>Off-Chain Fee: </strong>up to @spark.MaxRoutingFee</li>
<li><strong>Service Fee: </strong>Spark's fixed @SparkSwapService.ServiceFeeBps bps (@FeeFormat.Percent(SparkSwapService.ServiceFeeBps * 100L)), charged on the Lightning route: part of the off-chain fee</li>
<li><strong>On-Chain Fee</strong> (from Spark to L1: the SSP's exit fee and the L1 broadcast): up to @spark.MaxExitFee</li>
</ul><br>
@:The node starts paying its Spark wallet (@spark.Identity) as you confirm, and LND keeps
@:trying routes for up to @spark.PaymentTimeoutMinutes minutes (the node's Spark payment timeout);
@:the swap shows as pending on the Swaps page meanwhile.
@:Once paid, the swap waits in the Spark wallet until the wallet is full (no room left for another swap under its max balance),
@:then exits with the wallet's other paid swaps in one on-chain transaction to the destination wallet, sharing its fee,
@:at exit speed @SparkSettings.ExitSpeedSummary.
@:Up to @spark.MaxSwapsInFlight Spark swaps of @confirmation.NodeName (its Spark max swaps in flight) are paid at once.<br><br>
}

@:Please confirm that you want to proceed.
}
</ConfirmationModal>

@inject ISwapsService SwapsService
@inject IToastService ToastService
Expand Down Expand Up @@ -230,7 +299,18 @@
private string? _noSparkNodesReason;
private Node? _selectedNode;
private string? _amountInNodeBtc;
private string _confirmationModalBody = string.Empty;
private SwapConfirmation? _confirmation;

/// <summary>What the confirmation shows: the swap, plus its quote, the error of a failed quote or Spark's caps</summary>
private sealed record SwapConfirmation(string Provider, string Direction, string Amount, string? NodeName, string? WalletName,
string? QuoteError = null, QuotedFees? Quote = null, SparkCaps? Spark = null);

/// <summary>The selected fees are only set when the quoted fee is above what the user selected</summary>
private sealed record QuotedFees(string ServiceFee, string? SelectedServiceFee, string OffChainFee, string? SelectedRoutingFee,
string OnChainFee, string TotalFees, string TotalCost, bool CouldEstimateRoutingFees);

private sealed record SparkCaps(string MaxRoutingFee, string MaxExitFee, string? Identity, int PaymentTimeoutMinutes,
int MaxSwapsInFlight);
private decimal _btcPrice;
private bool _showAdvancedOptions = false;
private int _swapPublicationDeadlineOffsetMinutes = Constants.IS_DEV_ENVIRONMENT ? 1 : 30;
Expand Down Expand Up @@ -421,28 +501,20 @@
var HTLC_SWEEP_FEE_SAT_ON_QUOTE_ERROR = _amountBtc * EnvironmentHelpers.GetOrDefault("HTLC_SWEEP_FEE_SAT_ON_QUOTE_ERROR", 0.015m);
var PREPAY_AMT_SAT_ON_QUOTE_ERROR = _amountBtc * EnvironmentHelpers.GetOrDefault("PREPAY_AMT_SAT_ON_QUOTE_ERROR", 0.005m);

var middleChunkMessage = $"<strong>- Provider:</strong> {_selectedProvider.GetDisplayName()}<br>" +
$"<strong>- Direction:</strong> {_selectedDirection}<br>" +
$"<strong>- Amount:</strong> {FormatBtcWithUsd(_amountBtc)}<br>" +
$"<strong>- Origin Node:</strong> {_selectedNode?.Name}<br>" +
$"<strong>- Destination Wallet:</strong> {_selectedWallet?.Name}<br><br>";

ArgumentNullException.ThrowIfNull(_selectedWallet, nameof(_selectedWallet));
ArgumentNullException.ThrowIfNull(_selectedNode, nameof(_selectedNode));

var swap = new SwapConfirmation(_selectedProvider.GetDisplayName(), _selectedDirection.ToString(),
FormatBtcWithUsd(_amountBtc), _selectedNode.Name, _selectedWallet.Name);

if (_selectedProvider == SwapProvider.Spark)
{
await ShowSparkConfirmationModal(middleChunkMessage);
await ShowSparkConfirmationModal(swap);
return;
}

var showErrorModal = async (string errorMessage) => {
_confirmationModalBody = "Quote was not successful because of the following error: <br><br>" +
$"<span style='color: red;'>{errorMessage}</span>" + "<br><br>" +
"The swap will be created with the following details:<br><br>" +
middleChunkMessage +
"<span style='color: orange'>The fees could not be estimated. Default values will be used.</span><br><br>" +
"<br>Please confirm that you want to proceed.";
_confirmation = swap with { QuoteError = errorMessage };

var data = new Dictionary<string, object>
{
Expand All @@ -466,36 +538,25 @@
var onChainFee = new Money(quote.OnChainFees);
var totalFees = new Money(quote.ServiceFees + quote.OffChainFees + quote.OnChainFees);

var selectedServiceFee = _maxServiceFeesPercent * _amountBtc / 100;
var serviceFeeChunkMessage = $"<li><strong>Service Fee:</strong> {FormatBtcWithUsd(serviceFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(serviceFee)})</li>";
if (serviceFee.ToUnit(MoneyUnit.BTC) > selectedServiceFee) {
serviceFeeChunkMessage += $"<li style='list-style-type: none;'><span style='color: orange;'> (You selected: {FormatBtcWithUsd(selectedServiceFee)}, it might not go through)</span></li>";
}
string WithPercent(Money fee) => $"{FormatBtcWithUsd(fee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(fee)})";

var selectedServiceFee = _maxServiceFeesPercent * _amountBtc / 100;
var selectedRoutingFee = _maxRoutingFeesPercent * _amountBtc / 100;
var routingFeeChunkMessage = $"<li><strong>Off-Chain Fee:</strong> {FormatBtcWithUsd(offChainFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(offChainFee)})</li>";
if (offChainFee.ToUnit(MoneyUnit.BTC) > selectedRoutingFee) {
routingFeeChunkMessage += $"<li style='list-style-type: none;'><span style='color: orange;'> (You selected: {FormatBtcWithUsd(selectedRoutingFee)}, it might not go through)</span></li>";
}
var totalFeesBtc = FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC));

_confirmationModalBody = $"You are about to create a new swap with the following details:<br><br>" +
middleChunkMessage +
$"<strong>- Estimated Fees:</strong><br>" +
"<ul>"+
serviceFeeChunkMessage +
routingFeeChunkMessage +
$"<li><strong>On-Chain Fee:</strong> {FormatBtcWithUsd(onChainFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(onChainFee)})</li>" +
$"<li><strong>Total:</strong> {FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(totalFees)})</li>" +
"</ul>"+
"<br>" +
$"<strong>- Estimated total cost:</strong> {FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC))} (Percentage of total swap: {Math.Round(totalFees.ToUnit(MoneyUnit.BTC) / _amountBtc * 100, 2)}%)<br>";

if (!quote.CouldEstimateRoutingFees)
_confirmation = swap with
{
_confirmationModalBody += "<br>" + $"<span style='color: orange;'><strong>Warning:</strong> Routing fees could not be estimated. The actual fees will be higher than 0.</span><br><br>";
}

_confirmationModalBody += $"<br>Please confirm that you want to proceed.";
Quote = new QuotedFees(
ServiceFee: WithPercent(serviceFee),
SelectedServiceFee: serviceFee.ToUnit(MoneyUnit.BTC) > selectedServiceFee ? FormatBtcWithUsd(selectedServiceFee) : null,
OffChainFee: WithPercent(offChainFee),
SelectedRoutingFee: offChainFee.ToUnit(MoneyUnit.BTC) > selectedRoutingFee ? FormatBtcWithUsd(selectedRoutingFee) : null,
OnChainFee: WithPercent(onChainFee),
TotalFees: WithPercent(totalFees),
TotalCost: $"{totalFeesBtc} (Percentage of total swap: {Math.Round(totalFees.ToUnit(MoneyUnit.BTC) / _amountBtc * 100, 2)}%)",
CouldEstimateRoutingFees: quote.CouldEstimateRoutingFees)
};

var data = new Dictionary<string, object>
{
{ "HtlcSweepFeeSat", quote.HtlcSweepFeeSat },
Expand All @@ -519,28 +580,21 @@
/// Spark has no up-front quote: the SSP quotes its exit fee for the leaves the payment brings in, so the
/// confirmation shows the caps the swap runs under instead
/// </summary>
private async Task ShowSparkConfirmationModal(string middleChunkMessage)
private async Task ShowSparkConfirmationModal(SwapConfirmation swap)
{
var maxRoutingFee = new Money(_maxRoutingFeesPercent * _amountBtc / 100, MoneyUnit.BTC);
var maxExitFee = new Money(SparkSettings.MaxExitFeeSats);
var maxSwapsInFlight = Math.Max(_selectedNode?.SparkMaxSwapsInFlight ?? 0, 1);

_confirmationModalBody = "You are about to create a new swap with the following details:<br><br>" +
middleChunkMessage +
"<strong>- Maximum fees:</strong><br>" +
"<ul>" +
$"<li><strong>Off-Chain Fee:</strong> up to {FormatBtcWithUsd(maxRoutingFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxRoutingFee)})</li>" +
$"<li><strong>Service Fee:</strong> Spark's fixed {SparkSwapService.ServiceFeeBps} bps ({FeeFormat.Percent(SparkSwapService.ServiceFeeBps * 100L)}), charged on the Lightning route: part of the off-chain fee</li>" +
$"<li><strong>On-Chain Fee</strong> (from Spark to L1: the SSP's exit fee and the L1 broadcast): up to {FormatBtcWithUsd(maxExitFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxExitFee)})</li>" +
"</ul><br>" +
$"The node starts paying its Spark wallet ({SparkIdentityOf(_selectedNode!)}) as you confirm, and LND keeps " +
$"trying routes for up to {SparkSettings.PaymentTimeoutFor(_selectedNode!)} minutes (the node's Spark payment timeout); " +
"the swap shows as pending on the Swaps page meanwhile. " +
"Once paid, the swap waits in the Spark wallet until the wallet is full (no room left for another swap under its max balance), " +
"then exits with the wallet's other paid swaps in one on-chain transaction to the destination wallet, sharing its fee, " +
$"at exit speed {SparkSettings.ExitSpeedSummary}. " +
$"Up to {maxSwapsInFlight} Spark swaps of {_selectedNode?.Name} (its Spark max swaps in flight) are paid at once.<br><br>" +
"Please confirm that you want to proceed.";
_confirmation = swap with
{
Spark = new SparkCaps(
MaxRoutingFee: $"{FormatBtcWithUsd(maxRoutingFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxRoutingFee)})",
MaxExitFee: $"{FormatBtcWithUsd(maxExitFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxExitFee)})",
Identity: SparkIdentityOf(_selectedNode!),
PaymentTimeoutMinutes: SparkSettings.PaymentTimeoutFor(_selectedNode!),
MaxSwapsInFlight: maxSwapsInFlight)
};

await _confirmationModal.ShowModal(new Dictionary<string, object>
{
Expand Down
Loading
Loading