Channel-open race with latent nil dereference

Open
#11,259 0 comments 3 reactions 1 assignee View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

  • #11288 by @Amirhosein — closed without merging

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
42/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
go
Domain
backend

Research direction

Start at lnwallet/channel.go restoreCommitState (around L1546-L1572) where RemoteCommitChainTip() is read from the DB while RemoteNextRevocation comes from a stale in-memory copy, then trace funding.(*Manager).advanceFundingState in the funding manager to find where discoverySignal is closed relative to NewLightningChannel. The issue's suggested fix is to delay closing discoverySignal until after NewLightningChannel returns, optionally adding a nil guard on pendingCommitPoint. Done means the funding goroutine finishes its DB read before the link goroutine can spawn, plus a regression test (the linked PoC archive shows how to force the interleaving). Note a linked PR (#11288) was closed unmerged — check that thread first to see whether the approach was rejected before starting.

Written by the indexing model from the issue text.

Description

Two goroutines on the channel-opening path work on different copies of the same OpenChannel. If they interleave in the wrong order, a nil dereference occurs.

This does not reproduce on a stock LND. It's a real latent bug but not a current DoS concern. The reproducer inserts a sleep into LND's code, extending the race window to demonstrate the bug.

Summary

A peer opens a channel and, before the funding transaction confirms, sends channel_ready followed by an update_add_htlc / commitment_signed pair. LND queues all three internally. When the funding transaction confirms, the funding goroutine reads pending commitment state from the database while holding a copy of the channel that was never refreshed, and whose RemoteNextRevocation is nil. If a link has been spawned and has processed the update_add_htlc and commitment_signed by the time that read happens, it finds a commit diff, takes a branch that dereferences the nil, and the process dies.

Root cause

The race and nil dereference happen in restoreCommitState:

pendingRemoteCommitDiff, err = lc.channelState.RemoteCommitChainTip()  // DB read
if err != nil && err != channeldb.ErrNoPendingCommit {
    return err
}
if pendingRemoteCommitDiff != nil {
    pendingCommitPoint := lc.channelState.RemoteNextRevocation         // IN-MEMORY field
    ...
    pendingRemoteKeyChain = DeriveCommitmentKeys(pendingCommitPoint, ...)  // no nil check
}

"Is there a pending commitment?" is read from the database. "What is the peer's next revocation point?" is read from the in-memory struct.

On a normal channel-open flow, the in-memory RemoteNextRevocation is always nil, and a nil-dereference would occur if the pendingRemoteCommitDiff != nil block ever ran. But that block doesn't run because RemoteCommitChainTip() always returns ErrNoPendingCommit. This makes perfect sense because we can't have a pending commit if the channel isn't fully open yet.

... or can we?

Why the in-memory field stays nil

When LND processes the channel_ready it does record the revocation point, but it's done in the goroutine that handles channel_ready, not the funding goroutine that runs the code above. The funding goroutine's in-memory copy of the channel remains stale with a nil RemoteNextRevocation.

So everything hinges on the RemoteCommitChainTip() DB lookup that guards the nil dereference.

The two goroutines that touch the DB entry
  • The funding goroutine. This is the goroutine that runs the above code once the funding transaction confirms. Note that discoverySignal is closed several frames deeper than the vulnerable read, and execution then returns and continues:
    advanceFundingState
      advancePendingChannelState
        handleFundingConfirmation
          close(discoverySignal)
      NewLightningChannel
        restoreCommitState
          RemoteCommitChainTip()  ->  ErrNoPendingCommit
    
  • The link goroutine. This goroutine doesn't get created until the funding goroutine does close(discoverySignal) and the peer sends a channel_ready. Then the link will process any subsequent commitment updates and update the relevant DB entry using AppendRemoteCommitChain.

For a short window the two goroutines can exist at the same time. And if the link goroutine runs faster and completes a full commitment update before the funding goroutine calls RemoteCommitChainTip(), then the above nil dereference will occur.

Triggering the race

A peer can trigger the race as follows:

  1. Open a channel to LND: open_channel / accept_channel / funding_created / funding_signed.
  2. Broadcast the funding transaction, but do not confirm it yet.
  3. Send channel_ready. This ensures the link goroutine will be created as soon as the funding goroutine does close(discoverySignal).
  4. Send a valid update_add_htlc and commitment_signed. LND queues these for the soon-to-be-created link goroutine.
  5. Confirm the funding transaction. The funding goroutine closes discoverySignal, triggering the creation of the link goroutine, and the race window begins. The link goroutine processes the queued update_add_htlc and commitment_signed, eventually calling AppendRemoteCommitChain.

If the link is able to call AppendRemoteCommitChain before the funding goroutine calls RemoteCommitChainTip(), the nil dereference occurs:

panic: runtime error: invalid memory address or nil pointer dereference

input.SingleTweakBytes                           script_utils.go:2993
lnwallet.DeriveCommitmentKeys                    commitment.go:125
lnwallet.(*LightningChannel).restoreCommitState  channel.go:1572
lnwallet.NewLightningChannel                     channel.go:1036
funding.(*Manager).advanceFundingState           manager.go:1124
created by funding.(*Manager).fundeeProcessFundingCreated
sequenceDiagram
    participant F as funding goroutine
    participant C as link goroutine
    participant DB as channel row

    Note over F,C: close(discoverySignal)
    par
        C->>DB: sign the commitment,<br/>AppendRemoteCommitChain writes a commit diff
    and
        F->>DB: restoreCommitState calls RemoteCommitChainTip
    end

    alt the diff was written first
        DB-->>F: a commit diff
        Note over F: takes the branch,<br/>dereferences its nil point, panics
    else the read happened first
        DB-->>F: ErrNoPendingCommit
        Note over F: skips the branch,<br/>channel opens normally
    end
Constructing a valid commitment without LND's per-commitment point

Step 4 looks impossible at first because the peer would need LND's per-commitment point to send a valid commitment_signed message, and LND hasn't sent the channel_ready containing that point yet.

The way around it is to choose channel parameters so that the commitment transaction contains no output that depends on that point:

field in open_channel value effect
channel_type option_static_remotekey the peer's to_remote output is the untweaked payment basepoint
push_msat 0 LND's to_local is 0 sat, so it is trimmed
feerate_per_kw 2,500 puts the received-HTLC trim threshold near 2.1k sat
HTLC amount 1,000,000 msat (1,000 sat) under that threshold, so the HTLC is trimmed too

The resulting commitment has a single output that uses the peer's untweaked basepoint, and there's no need for LND's per-commitment point.

Reproducing

This program demonstrates the bug on a patched LND.

lnd-stale-revocation-poc.tar.gz

Run it as follows:

docker build -t lnd-stale-revocation-poc .
docker run --rm lnd-stale-revocation-poc

The image applies a patch to LND that inserts a sleep to extend the race window and reliably reproduce the crash. The default sleep is 200ms but can be adjusted by setting the LND_POC_SLEEP_MS environment variable to something else. Setting it to 0 shows that the nil dereference currently never occurs on a stock LND.

Impact

This is a real race condition with a latent nil-dereference that currently never occurs on a stock LND. Over hundreds of attempts I was unable to crash LND a single time without introducing a sleep. I tried many ways, including pinning LND to a single core and introducing contention from other goroutines.

This is still worth fixing because future code changes could affect the timing of the race and make the nil-dereference more accessible.

Suggested fix

discoverySignal should not be closed until the funding goroutine is past NewLightningChannel. That ensures the link can't start up until after the funding goroutine is done checking the DB.

A nil guard in restoreCommitState avoids the panic and may be worth adding as defense in depth, but it's not a great solution on its own because it leaves the funding goroutine building a channel state machine from a copy it already knows is stale.

Discovery

Found by @dergoegge using smite with an experimental hypervisor that forces unusual thread interleavings.

Dominant language
Go
Stars
8.2k
Forks
2.3k
Avg merge
1d 11h
Merged PRs (30d)
103

Getting set up

  • Ships a Dockerfile or Docker Compose file
  • Has a pull request template
  • No contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from lightningnetwork/lnd

All issues in lightningnetwork/lnd

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.