SS2022 inbound: Fix data races and duplicate acceptance when decoding one UDP session concurrently

Packets of one client session can be processed by two inbound workers at
the same time (e.g. the client's old and new source address after a NAT
rebinding). The sliding window was checked and updated in two separate
critical sections, and clientBodyCipher and the session's User were read
without the lock, so the same packet ID could be accepted more than once
and go test -race reported data races.

Re-check the window and publish the cached body cipher in one critical
section after the packet is fully validated, and always initialize the
session's User under the lock.
This commit is contained in:
Roman Rublev
2026-11-26 21:09:05 +08:00
committed by Fangliding
parent e17392a96e
commit 2ac088f627
5 changed files with 97 additions and 22 deletions
@@ -496,3 +496,60 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
})
}
}
// Packets of one client session may be decoded concurrently, e.g. by the inbound
// workers of the client's old and new source address after a NAT rebinding.
func TestUDPServerConcurrentDecodeSameSession(t *testing.T) {
for _, methodName := range []string{MethodAES128GCM, MethodAES256GCM, MethodChaCha20Poly1305} {
t.Run(methodName, func(t *testing.T) {
method, err := GetCipherMethod(methodName)
common.Must(err)
rawKey := make([]byte, method.KeySaltLength)
_, _ = rand.Read(rawKey)
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
common.Must(err)
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute)
common.Must(err)
session, err := clientCodec.NewClientSession()
common.Must(err)
dest := net.UDPDestination(net.LocalHostIP, net.Port(443))
packets := make([][]byte, 256)
for i := range packets {
pkt, err := session.EncodePacket(dest, []byte("payload"))
common.Must(err)
packets[i] = append([]byte(nil), pkt.Bytes()...)
pkt.Release()
}
const workers = 4
var wg sync.WaitGroup
var mu sync.Mutex
accepted := make([]int, len(packets))
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
// Every worker sees every packet, so each packet must be accepted exactly once.
for i, pkt := range packets {
if _, err := serverCodec.DecodePacket(pkt); err == nil {
mu.Lock()
accepted[i]++
mu.Unlock()
} else if err != ErrPacketIdNotUnique {
t.Errorf("packet %d: unexpected error: %v", i, err)
}
}
}()
}
wg.Wait()
for i, n := range accepted {
if n != 1 {
t.Fatalf("packet %d accepted %d times, want 1", i, n)
}
}
})
}
}