Skip to content

Commit d95962c

Browse files
gballetfjl
authored andcommitted
whisper/whisperv6: remove aesnonce (#15578)
As per EIP-627, the salt for symmetric encryption is now part of the payload. This commit does that.
1 parent b587427 commit d95962c

8 files changed

Lines changed: 168 additions & 73 deletions

File tree

‎whisper/whisperv6/doc.go‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,15 @@ import (
3636

3737
const (
3838
EnvelopeVersion = uint64(0)
39-
ProtocolVersion = uint64(5)
40-
ProtocolVersionStr = "5.0"
39+
ProtocolVersion = uint64(6)
40+
ProtocolVersionStr = "6.0"
4141
ProtocolName = "shh"
4242

4343
statusCode = 0 // used by whisper protocol
4444
messagesCode = 1 // normal whisper message
4545
p2pCode = 2 // peer-to-peer message (to be consumed by the peer, but not forwarded any further)
4646
p2pRequestCode = 3 // peer-to-peer message, used by Dapp protocol
47-
NumberOfMessageCodes = 64
47+
NumberOfMessageCodes = 128
4848

4949
paddingMask = byte(3)
5050
signatureFlag = byte(4)
@@ -67,6 +67,8 @@ const (
6767

6868
DefaultTTL = 50 // seconds
6969
SynchAllowance = 10 // seconds
70+
71+
EnvelopeHeaderLength = 20
7072
)
7173

7274
type unknownVersionError uint64

‎whisper/whisperv6/envelope.go‎

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,12 @@ import (
3636
// Envelope represents a clear-text data packet to transmit through the Whisper
3737
// network. Its contents may or may not be encrypted and signed.
3838
type Envelope struct {
39-
Version []byte
40-
Expiry uint32
41-
TTL uint32
42-
Topic TopicType
43-
AESNonce []byte
44-
Data []byte
45-
Nonce uint64
39+
Version []byte
40+
Expiry uint32
41+
TTL uint32
42+
Topic TopicType
43+
Data []byte
44+
Nonce uint64
4645

4746
pow float64 // Message-specific PoW as described in the Whisper specification.
4847
hash common.Hash // Cached hash of the envelope to avoid rehashing every time.
@@ -51,26 +50,25 @@ type Envelope struct {
5150

5251
// size returns the size of envelope as it is sent (i.e. public fields only)
5352
func (e *Envelope) size() int {
54-
return 20 + len(e.Version) + len(e.AESNonce) + len(e.Data)
53+
return EnvelopeHeaderLength + len(e.Version) + len(e.Data)
5554
}
5655

5756
// rlpWithoutNonce returns the RLP encoded envelope contents, except the nonce.
5857
func (e *Envelope) rlpWithoutNonce() []byte {
59-
res, _ := rlp.EncodeToBytes([]interface{}{e.Version, e.Expiry, e.TTL, e.Topic, e.AESNonce, e.Data})
58+
res, _ := rlp.EncodeToBytes([]interface{}{e.Version, e.Expiry, e.TTL, e.Topic, e.Data})
6059
return res
6160
}
6261

6362
// NewEnvelope wraps a Whisper message with expiration and destination data
6463
// included into an envelope for network forwarding.
65-
func NewEnvelope(ttl uint32, topic TopicType, aesNonce []byte, msg *sentMessage) *Envelope {
64+
func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage) *Envelope {
6665
env := Envelope{
67-
Version: make([]byte, 1),
68-
Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()),
69-
TTL: ttl,
70-
Topic: topic,
71-
AESNonce: aesNonce,
72-
Data: msg.Raw,
73-
Nonce: 0,
66+
Version: make([]byte, 1),
67+
Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()),
68+
TTL: ttl,
69+
Topic: topic,
70+
Data: msg.Raw,
71+
Nonce: 0,
7472
}
7573

7674
if EnvelopeVersion < 256 {
@@ -82,14 +80,6 @@ func NewEnvelope(ttl uint32, topic TopicType, aesNonce []byte, msg *sentMessage)
8280
return &env
8381
}
8482

85-
func (e *Envelope) IsSymmetric() bool {
86-
return len(e.AESNonce) > 0
87-
}
88-
89-
func (e *Envelope) isAsymmetric() bool {
90-
return !e.IsSymmetric()
91-
}
92-
9383
func (e *Envelope) Ver() uint64 {
9484
return bytesToUintLittleEndian(e.Version)
9585
}
@@ -209,7 +199,7 @@ func (e *Envelope) OpenAsymmetric(key *ecdsa.PrivateKey) (*ReceivedMessage, erro
209199
// OpenSymmetric tries to decrypt an envelope, potentially encrypted with a particular key.
210200
func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error) {
211201
msg = &ReceivedMessage{Raw: e.Data}
212-
err = msg.decryptSymmetric(key, e.AESNonce)
202+
err = msg.decryptSymmetric(key)
213203
if err != nil {
214204
msg = nil
215205
}
@@ -218,12 +208,18 @@ func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error) {
218208

219209
// Open tries to decrypt an envelope, and populates the message fields in case of success.
220210
func (e *Envelope) Open(watcher *Filter) (msg *ReceivedMessage) {
221-
if e.isAsymmetric() {
211+
// The API interface forbids filters doing both symmetric and
212+
// asymmetric encryption.
213+
if watcher.expectsAsymmetricEncryption() && watcher.expectsSymmetricEncryption() {
214+
return nil
215+
}
216+
217+
if watcher.expectsAsymmetricEncryption() {
222218
msg, _ = e.OpenAsymmetric(watcher.KeyAsym)
223219
if msg != nil {
224220
msg.Dst = &watcher.KeyAsym.PublicKey
225221
}
226-
} else if e.IsSymmetric() {
222+
} else if watcher.expectsSymmetricEncryption() {
227223
msg, _ = e.OpenSymmetric(watcher.KeySym)
228224
if msg != nil {
229225
msg.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym)

‎whisper/whisperv6/envelope_test.go‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
// Contains the tests associated with the Whisper protocol Envelope object.
18+
19+
package whisperv6
20+
21+
import (
22+
mrand "math/rand"
23+
"testing"
24+
25+
"github.com/ethereum/go-ethereum/crypto"
26+
)
27+
28+
func TestEnvelopeOpenAcceptsOnlyOneKeyTypeInFilter(t *testing.T) {
29+
symKey := make([]byte, aesKeyLength)
30+
mrand.Read(symKey)
31+
32+
asymKey, err := crypto.GenerateKey()
33+
if err != nil {
34+
t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
35+
}
36+
37+
params := MessageParams{
38+
PoW: 0.01,
39+
WorkTime: 1,
40+
TTL: uint32(mrand.Intn(1024)),
41+
Payload: make([]byte, 50),
42+
KeySym: symKey,
43+
Dst: nil,
44+
}
45+
46+
mrand.Read(params.Payload)
47+
48+
msg, err := NewSentMessage(&params)
49+
if err != nil {
50+
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
51+
}
52+
53+
e, err := msg.Wrap(&params)
54+
if err != nil {
55+
t.Fatalf("Failed to Wrap the message in an envelope with seed %d: %s", seed, err)
56+
}
57+
58+
f := Filter{KeySym: symKey, KeyAsym: asymKey}
59+
60+
decrypted := e.Open(&f)
61+
if decrypted != nil {
62+
t.Fatalf("Managed to decrypt a message with an invalid filter, seed %d", seed)
63+
}
64+
}

‎whisper/whisperv6/filter.go‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ func NewFilters(w *Whisper) *Filters {
5353
}
5454

5555
func (fs *Filters) Install(watcher *Filter) (string, error) {
56+
if watcher.KeySym != nil && watcher.KeyAsym != nil {
57+
return "", fmt.Errorf("filters must choose between symmetric and asymmetric keys")
58+
}
59+
5660
if watcher.Messages == nil {
5761
watcher.Messages = make(map[common.Hash]*ReceivedMessage)
5862
}
@@ -175,6 +179,9 @@ func (f *Filter) Retrieve() (all []*ReceivedMessage) {
175179
return all
176180
}
177181

182+
// MatchMessage checks if the filter matches an already decrypted
183+
// message (i.e. a Message that has already been handled by
184+
// MatchEnvelope when checked by a previous filter)
178185
func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
179186
if f.PoW > 0 && msg.PoW < f.PoW {
180187
return false
@@ -188,17 +195,15 @@ func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
188195
return false
189196
}
190197

198+
// MatchEvelope checks if it's worth decrypting the message. If
199+
// it returns `true`, client code is expected to attempt decrypting
200+
// the message and subsequently call MatchMessage.
191201
func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
192202
if f.PoW > 0 && envelope.pow < f.PoW {
193203
return false
194204
}
195205

196-
if f.expectsAsymmetricEncryption() && envelope.isAsymmetric() {
197-
return f.MatchTopic(envelope.Topic)
198-
} else if f.expectsSymmetricEncryption() && envelope.IsSymmetric() {
199-
return f.MatchTopic(envelope.Topic)
200-
}
201-
return false
206+
return f.MatchTopic(envelope.Topic)
202207
}
203208

204209
func (f *Filter) MatchTopic(topic TopicType) bool {

‎whisper/whisperv6/filter_test.go‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,36 @@ func TestInstallIdenticalFilters(t *testing.T) {
229229
}
230230
}
231231

232+
func TestInstallFilterWithSymAndAsymKeys(t *testing.T) {
233+
InitSingleTest()
234+
235+
w := New(&Config{})
236+
filters := NewFilters(w)
237+
filter1, _ := generateFilter(t, true)
238+
239+
asymKey, err := crypto.GenerateKey()
240+
if err != nil {
241+
t.Fatalf("Unable to create asymetric keys: %v", err)
242+
}
243+
244+
// Copy the first filter since some of its fields
245+
// are randomly gnerated.
246+
filter := &Filter{
247+
KeySym: filter1.KeySym,
248+
KeyAsym: asymKey,
249+
Topics: filter1.Topics,
250+
PoW: filter1.PoW,
251+
AllowP2P: filter1.AllowP2P,
252+
Messages: make(map[common.Hash]*ReceivedMessage),
253+
}
254+
255+
_, err = filters.Install(filter)
256+
257+
if err == nil {
258+
t.Fatalf("Error detecting that a filter had both an asymmetric and symmetric key, with seed %d", seed)
259+
}
260+
}
261+
232262
func TestComparePubKey(t *testing.T) {
233263
InitSingleTest()
234264

@@ -312,12 +342,6 @@ func TestMatchEnvelope(t *testing.T) {
312342
t.Fatalf("failed MatchEnvelope() symmetric with seed %d.", seed)
313343
}
314344

315-
// asymmetric + matching topic: mismatch
316-
match = fasym.MatchEnvelope(env)
317-
if match {
318-
t.Fatalf("failed MatchEnvelope() asymmetric with seed %d.", seed)
319-
}
320-
321345
// symmetric + matching topic + insufficient PoW: mismatch
322346
fsym.PoW = env.PoW() + 1.0
323347
match = fsym.MatchEnvelope(env)

‎whisper/whisperv6/message.go‎

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ type ReceivedMessage struct {
6161
Payload []byte
6262
Padding []byte
6363
Signature []byte
64+
Salt []byte
6465

6566
PoW float64 // Proof of work as described in the Whisper spec
6667
Sent uint32 // Time when the message was posted into the network
@@ -196,31 +197,31 @@ func (msg *sentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error {
196197

197198
// encryptSymmetric encrypts a message with a topic key, using AES-GCM-256.
198199
// nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
199-
func (msg *sentMessage) encryptSymmetric(key []byte) (nonce []byte, err error) {
200+
func (msg *sentMessage) encryptSymmetric(key []byte) (err error) {
200201
if !validateSymmetricKey(key) {
201-
return nil, errors.New("invalid key provided for symmetric encryption")
202+
return errors.New("invalid key provided for symmetric encryption")
202203
}
203204

204205
block, err := aes.NewCipher(key)
205206
if err != nil {
206-
return nil, err
207+
return err
207208
}
208209
aesgcm, err := cipher.NewGCM(block)
209210
if err != nil {
210-
return nil, err
211+
return err
211212
}
212213

213214
// never use more than 2^32 random nonces with a given key
214-
nonce = make([]byte, aesgcm.NonceSize())
215-
_, err = crand.Read(nonce)
215+
salt := make([]byte, aesgcm.NonceSize())
216+
_, err = crand.Read(salt)
216217
if err != nil {
217-
return nil, err
218-
} else if !validateSymmetricKey(nonce) {
219-
return nil, errors.New("crypto/rand failed to generate nonce")
218+
return err
219+
} else if !validateSymmetricKey(salt) {
220+
return errors.New("crypto/rand failed to generate salt")
220221
}
221222

222-
msg.Raw = aesgcm.Seal(nil, nonce, msg.Raw, nil)
223-
return nonce, nil
223+
msg.Raw = append(aesgcm.Seal(nil, salt, msg.Raw, nil), salt...)
224+
return nil
224225
}
225226

226227
// Wrap bundles the message into an Envelope to transmit over the network.
@@ -233,19 +234,18 @@ func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err er
233234
return nil, err
234235
}
235236
}
236-
var nonce []byte
237237
if options.Dst != nil {
238238
err = msg.encryptAsymmetric(options.Dst)
239239
} else if options.KeySym != nil {
240-
nonce, err = msg.encryptSymmetric(options.KeySym)
240+
err = msg.encryptSymmetric(options.KeySym)
241241
} else {
242242
err = errors.New("unable to encrypt the message: neither symmetric nor assymmetric key provided")
243243
}
244244
if err != nil {
245245
return nil, err
246246
}
247247

248-
envelope = NewEnvelope(options.TTL, options.Topic, nonce, msg)
248+
envelope = NewEnvelope(options.TTL, options.Topic, msg)
249249
if err = envelope.Seal(options); err != nil {
250250
return nil, err
251251
}
@@ -254,7 +254,14 @@ func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err er
254254

255255
// decryptSymmetric decrypts a message with a topic key, using AES-GCM-256.
256256
// nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
257-
func (msg *ReceivedMessage) decryptSymmetric(key []byte, nonce []byte) error {
257+
func (msg *ReceivedMessage) decryptSymmetric(key []byte) error {
258+
// In v6, symmetric messages are expected to contain the 12-byte
259+
// "salt" at the end of the payload.
260+
if len(msg.Raw) < AESNonceLength {
261+
return errors.New("missing salt or invalid payload in symmetric message")
262+
}
263+
salt := msg.Raw[len(msg.Raw)-AESNonceLength:]
264+
258265
block, err := aes.NewCipher(key)
259266
if err != nil {
260267
return err
@@ -263,15 +270,16 @@ func (msg *ReceivedMessage) decryptSymmetric(key []byte, nonce []byte) error {
263270
if err != nil {
264271
return err
265272
}
266-
if len(nonce) != aesgcm.NonceSize() {
267-
log.Error("decrypting the message", "AES nonce size", len(nonce))
268-
return errors.New("wrong AES nonce size")
273+
if len(salt) != aesgcm.NonceSize() {
274+
log.Error("decrypting the message", "AES salt size", len(salt))
275+
return errors.New("wrong AES salt size")
269276
}
270-
decrypted, err := aesgcm.Open(nil, nonce, msg.Raw, nil)
277+
decrypted, err := aesgcm.Open(nil, salt, msg.Raw[:len(msg.Raw)-AESNonceLength], nil)
271278
if err != nil {
272279
return err
273280
}
274281
msg.Raw = decrypted
282+
msg.Salt = salt
275283
return nil
276284
}
277285

0 commit comments

Comments
 (0)