Skip to content

Commit 340a53a

Browse files
janoszelig
authored andcommitted
swarm/pss: fix data race on HandshakeController.symKeyIndex (#19162)
* swarm/pss: fix data race on HandshakeController.symKeyIndex The HandshakeController.symKeyIndex map was accessed concurrently. Since insufficient test coverage the race is not detected every time. However, running TestClientHandshake a 100 times seems to be enough to reproduce the race. Note: I've chosen HandshakeController.lock to protect HandshakeController.symKeyIndex as that was already protected in a few functions by that lock. Additionally: - removed unused testStore - enabled tests in handshake_test.go as they pass - removed code duplication by adding getSymKey() * swarm/pss: fix a data race on HandshakeController.keyC * swarm/pss: fix data races with on Pss.symKeyPool
1 parent badaf43 commit 340a53a

4 files changed

Lines changed: 55 additions & 48 deletions

File tree

‎swarm/pss/client/client_test.go‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"fmt"
2424
"math/rand"
2525
"os"
26-
"sync"
2726
"testing"
2827
"time"
2928

@@ -286,18 +285,3 @@ func newServices() adapters.Services {
286285
},
287286
}
288287
}
289-
290-
// copied from swarm/network/protocol_test_go
291-
type testStore struct {
292-
sync.Mutex
293-
294-
values map[string][]byte
295-
}
296-
297-
func (t *testStore) Load(key string) ([]byte, error) {
298-
return nil, nil
299-
}
300-
301-
func (t *testStore) Save(key string, v []byte) error {
302-
return nil
303-
}

‎swarm/pss/handshake.go‎

Lines changed: 52 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ func NewHandshakeParams() *HandshakeParams {
106106
type HandshakeController struct {
107107
pss *Pss
108108
keyC map[string]chan []string // adds a channel to report when a handshake succeeds
109+
keyCMu sync.Mutex // protects keyC map
109110
lock sync.Mutex
110111
symKeyRequestTimeout time.Duration
111112
symKeyExpiryTimeout time.Duration
@@ -165,9 +166,9 @@ func (ctl *HandshakeController) validKeys(pubkeyid string, topic *Topic, in bool
165166

166167
for _, key := range *keystore {
167168
if key.limit <= key.count {
168-
ctl.releaseKey(*key.symKeyID, topic)
169+
ctl.releaseKeyNoLock(*key.symKeyID, topic)
169170
} else if !key.expiredAt.IsZero() && key.expiredAt.Before(now) {
170-
ctl.releaseKey(*key.symKeyID, topic)
171+
ctl.releaseKeyNoLock(*key.symKeyID, topic)
171172
} else {
172173
validkeys = append(validkeys, key.symKeyID)
173174
}
@@ -205,15 +206,23 @@ func (ctl *HandshakeController) updateKeys(pubkeyid string, topic *Topic, in boo
205206
limit: limit,
206207
}
207208
*keystore = append(*keystore, storekey)
209+
ctl.pss.mx.Lock()
208210
ctl.pss.symKeyPool[*storekey.symKeyID][*topic].protected = true
211+
ctl.pss.mx.Unlock()
209212
}
210213
for i := 0; i < len(*keystore); i++ {
211214
ctl.symKeyIndex[*(*keystore)[i].symKeyID] = &((*keystore)[i])
212215
}
213216
}
214217

215-
// Expire a symmetric key, making it elegible for garbage collection
216218
func (ctl *HandshakeController) releaseKey(symkeyid string, topic *Topic) bool {
219+
ctl.lock.Lock()
220+
defer ctl.lock.Unlock()
221+
return ctl.releaseKeyNoLock(symkeyid, topic)
222+
}
223+
224+
// Expire a symmetric key, making it eligible for garbage collection
225+
func (ctl *HandshakeController) releaseKeyNoLock(symkeyid string, topic *Topic) bool {
217226
if ctl.symKeyIndex[symkeyid] == nil {
218227
log.Debug("no symkey", "symkeyid", symkeyid)
219228
return false
@@ -276,30 +285,49 @@ func (ctl *HandshakeController) clean() {
276285
}
277286
}
278287

288+
func (ctl *HandshakeController) getSymKey(symkeyid string) *handshakeKey {
289+
ctl.lock.Lock()
290+
defer ctl.lock.Unlock()
291+
return ctl.symKeyIndex[symkeyid]
292+
}
293+
279294
// Passed as a PssMsg handler for the topic handshake is activated on
280295
// Handles incoming key exchange messages and
281-
// ccunts message usage by symmetric key (expiry limit control)
296+
// counts message usage by symmetric key (expiry limit control)
282297
// Only returns error if key handler fails
283298
func (ctl *HandshakeController) handler(msg []byte, p *p2p.Peer, asymmetric bool, symkeyid string) error {
284-
if !asymmetric {
285-
if ctl.symKeyIndex[symkeyid] != nil {
286-
if ctl.symKeyIndex[symkeyid].count >= ctl.symKeyIndex[symkeyid].limit {
287-
return fmt.Errorf("discarding message using expired key: %s", symkeyid)
299+
if asymmetric {
300+
keymsg := &handshakeMsg{}
301+
err := rlp.DecodeBytes(msg, keymsg)
302+
if err == nil {
303+
err := ctl.handleKeys(symkeyid, keymsg)
304+
if err != nil {
305+
log.Error("handlekeys fail", "error", err)
288306
}
289-
ctl.symKeyIndex[symkeyid].count++
290-
log.Trace("increment symkey recv use", "symsymkeyid", symkeyid, "count", ctl.symKeyIndex[symkeyid].count, "limit", ctl.symKeyIndex[symkeyid].limit, "receiver", common.ToHex(crypto.FromECDSAPub(ctl.pss.PublicKey())))
307+
return err
291308
}
292309
return nil
293310
}
294-
keymsg := &handshakeMsg{}
295-
err := rlp.DecodeBytes(msg, keymsg)
296-
if err == nil {
297-
err := ctl.handleKeys(symkeyid, keymsg)
298-
if err != nil {
299-
log.Error("handlekeys fail", "error", err)
300-
}
301-
return err
311+
return ctl.registerSymKeyUse(symkeyid)
312+
}
313+
314+
func (ctl *HandshakeController) registerSymKeyUse(symkeyid string) error {
315+
ctl.lock.Lock()
316+
defer ctl.lock.Unlock()
317+
318+
symKey, ok := ctl.symKeyIndex[symkeyid]
319+
if !ok {
320+
return nil
302321
}
322+
323+
if symKey.count >= symKey.limit {
324+
return fmt.Errorf("symetric key expired (id: %s)", symkeyid)
325+
}
326+
symKey.count++
327+
328+
receiver := common.ToHex(crypto.FromECDSAPub(ctl.pss.PublicKey()))
329+
log.Trace("increment symkey recv use", "symsymkeyid", symkeyid, "count", symKey.count, "limit", symKey.limit, "receiver", receiver)
330+
303331
return nil
304332
}
305333

@@ -417,6 +445,8 @@ func (ctl *HandshakeController) sendKey(pubkeyid string, topic *Topic, keycount
417445

418446
// Enables callback for keys received from a key exchange request
419447
func (ctl *HandshakeController) alertHandshake(pubkeyid string, symkeys []string) chan []string {
448+
ctl.keyCMu.Lock()
449+
defer ctl.keyCMu.Unlock()
420450
if len(symkeys) > 0 {
421451
if _, ok := ctl.keyC[pubkeyid]; ok {
422452
ctl.keyC[pubkeyid] <- symkeys
@@ -519,7 +549,7 @@ func (api *HandshakeAPI) GetHandshakeKeys(pubkeyid string, topic Topic, in bool,
519549
// Returns the amount of messages the specified symmetric key
520550
// is still valid for under the handshake scheme
521551
func (api *HandshakeAPI) GetHandshakeKeyCapacity(symkeyid string) (uint16, error) {
522-
storekey := api.ctrl.symKeyIndex[symkeyid]
552+
storekey := api.ctrl.getSymKey(symkeyid)
523553
if storekey == nil {
524554
return 0, fmt.Errorf("invalid symkey id %s", symkeyid)
525555
}
@@ -529,7 +559,7 @@ func (api *HandshakeAPI) GetHandshakeKeyCapacity(symkeyid string) (uint16, error
529559
// Returns the byte representation of the public key in ascii hex
530560
// associated with the given symmetric key
531561
func (api *HandshakeAPI) GetHandshakePublicKey(symkeyid string) (string, error) {
532-
storekey := api.ctrl.symKeyIndex[symkeyid]
562+
storekey := api.ctrl.getSymKey(symkeyid)
533563
if storekey == nil {
534564
return "", fmt.Errorf("invalid symkey id %s", symkeyid)
535565
}
@@ -555,12 +585,8 @@ func (api *HandshakeAPI) ReleaseHandshakeKey(pubkeyid string, topic Topic, symke
555585
// for message expiry control
556586
func (api *HandshakeAPI) SendSym(symkeyid string, topic Topic, msg hexutil.Bytes) (err error) {
557587
err = api.ctrl.pss.SendSym(symkeyid, topic, msg[:])
558-
if api.ctrl.symKeyIndex[symkeyid] != nil {
559-
if api.ctrl.symKeyIndex[symkeyid].count >= api.ctrl.symKeyIndex[symkeyid].limit {
560-
return errors.New("attempted send with expired key")
561-
}
562-
api.ctrl.symKeyIndex[symkeyid].count++
563-
log.Trace("increment symkey send use", "symkeyid", symkeyid, "count", api.ctrl.symKeyIndex[symkeyid].count, "limit", api.ctrl.symKeyIndex[symkeyid].limit, "receiver", common.ToHex(crypto.FromECDSAPub(api.ctrl.pss.PublicKey())))
588+
if otherErr := api.ctrl.registerSymKeyUse(symkeyid); otherErr != nil {
589+
return otherErr
564590
}
565591
return err
566592
}

‎swarm/pss/handshake_test.go‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
// +build foo
18-
1917
package pss
2018

2119
import (
@@ -30,7 +28,6 @@ import (
3028
// asymmetrical key exchange between two directly connected peers
3129
// full address, partial address (8 bytes) and empty address
3230
func TestHandshake(t *testing.T) {
33-
t.Skip("handshakes are not adapted to current pss core code")
3431
t.Run("32", testHandshake)
3532
t.Run("8", testHandshake)
3633
t.Run("0", testHandshake)
@@ -47,7 +44,7 @@ func testHandshake(t *testing.T) {
4744

4845
// set up two nodes directly connected
4946
// (we are not testing pss routing here)
50-
clients, err := setupNetwork(2)
47+
clients, err := setupNetwork(2, true)
5148
if err != nil {
5249
t.Fatal(err)
5350
}

‎swarm/pss/keystore.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,8 @@ func (ks *Pss) processAsym(envelope *whisper.Envelope) (*whisper.ReceivedMessage
210210
// - it is not marked as protected
211211
// - it is not in the incoming decryption cache
212212
func (ks *Pss) cleanKeys() (count int) {
213+
ks.mx.Lock()
214+
defer ks.mx.Unlock()
213215
for keyid, peertopics := range ks.symKeyPool {
214216
var expiredtopics []Topic
215217
for topic, psp := range peertopics {
@@ -229,10 +231,8 @@ func (ks *Pss) cleanKeys() (count int) {
229231
}
230232
}
231233
for _, topic := range expiredtopics {
232-
ks.mx.Lock()
233234
delete(ks.symKeyPool[keyid], topic)
234235
log.Trace("symkey cleanup deletion", "symkeyid", keyid, "topic", topic, "val", ks.symKeyPool[keyid])
235-
ks.mx.Unlock()
236236
count++
237237
}
238238
}

0 commit comments

Comments
 (0)