aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/pss/keystore.go
blob: 510d21bcfdc651da3fa5a01c6df49c3707435cea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package pss

import (
    "crypto/ecdsa"
    "errors"
    "fmt"
    "sync"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/metrics"
    "github.com/ethereum/go-ethereum/swarm/log"
    whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
)

type KeyStore struct {
    w *whisper.Whisper // key and encryption backend

    mx                       sync.RWMutex
    pubKeyPool               map[string]map[Topic]*pssPeer // mapping of hex public keys to peer address by topic.
    symKeyPool               map[string]map[Topic]*pssPeer // mapping of symkeyids to peer address by topic.
    symKeyDecryptCache       []*string                     // fast lookup of symkeys recently used for decryption; last used is on top of stack
    symKeyDecryptCacheCursor int                           // modular cursor pointing to last used, wraps on symKeyDecryptCache array
}

func loadKeyStore() *KeyStore {
    return &KeyStore{
        w: whisper.New(&whisper.DefaultConfig),

        pubKeyPool:         make(map[string]map[Topic]*pssPeer),
        symKeyPool:         make(map[string]map[Topic]*pssPeer),
        symKeyDecryptCache: make([]*string, defaultSymKeyCacheCapacity),
    }
}

func (ks *KeyStore) isSymKeyStored(key string) bool {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    var ok bool
    _, ok = ks.symKeyPool[key]
    return ok
}

func (ks *KeyStore) isPubKeyStored(key string) bool {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    var ok bool
    _, ok = ks.pubKeyPool[key]
    return ok
}

func (ks *KeyStore) getPeerSym(symkeyid string, topic Topic) (*pssPeer, bool) {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    psp, ok := ks.symKeyPool[symkeyid][topic]
    return psp, ok
}

func (ks *KeyStore) getPeerPub(pubkeyid string, topic Topic) (*pssPeer, bool) {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    psp, ok := ks.pubKeyPool[pubkeyid][topic]
    return psp, ok
}

// Links a peer ECDSA public key to a topic.
// This is required for asymmetric message exchange on the given topic.
// The value in `address` will be used as a routing hint for the public key / topic association.
func (ks *KeyStore) SetPeerPublicKey(pubkey *ecdsa.PublicKey, topic Topic, address PssAddress) error {
    if err := validateAddress(address); err != nil {
        return err
    }
    pubkeybytes := crypto.FromECDSAPub(pubkey)
    if len(pubkeybytes) == 0 {
        return fmt.Errorf("invalid public key: %v", pubkey)
    }
    pubkeyid := common.ToHex(pubkeybytes)
    psp := &pssPeer{
        address: address,
    }
    ks.mx.Lock()
    if _, ok := ks.pubKeyPool[pubkeyid]; !ok {
        ks.pubKeyPool[pubkeyid] = make(map[Topic]*pssPeer)
    }
    ks.pubKeyPool[pubkeyid][topic] = psp
    ks.mx.Unlock()
    log.Trace("added pubkey", "pubkeyid", pubkeyid, "topic", topic, "address", address)
    return nil
}

// adds a symmetric key to the pss key pool, and optionally adds the key to the
// collection of keys used to attempt symmetric decryption of incoming messages
func (ks *KeyStore) addSymmetricKeyToPool(keyid string, topic Topic, address PssAddress, addtocache bool, protected bool) {
    psp := &pssPeer{
        address:   address,
        protected: protected,
    }
    ks.mx.Lock()
    if _, ok := ks.symKeyPool[keyid]; !ok {
        ks.symKeyPool[keyid] = make(map[Topic]*pssPeer)
    }
    ks.symKeyPool[keyid][topic] = psp
    ks.mx.Unlock()
    if addtocache {
        ks.symKeyDecryptCacheCursor++
        ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = &keyid
    }
}

// Returns all recorded topic and address combination for a specific public key
func (ks *KeyStore) GetPublickeyPeers(keyid string) (topic []Topic, address []PssAddress, err error) {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    for t, peer := range ks.pubKeyPool[keyid] {
        topic = append(topic, t)
        address = append(address, peer.address)
    }
    return topic, address, nil
}

func (ks *KeyStore) getPeerAddress(keyid string, topic Topic) (PssAddress, error) {
    ks.mx.RLock()
    defer ks.mx.RUnlock()
    if peers, ok := ks.pubKeyPool[keyid]; ok {
        if t, ok := peers[topic]; ok {
            return t.address, nil
        }
    }
    return nil, fmt.Errorf("peer with pubkey %s, topic %x not found", keyid, topic)
}

// Attempt to decrypt, validate and unpack a symmetrically encrypted message.
// If successful, returns the unpacked whisper ReceivedMessage struct
// encapsulating the decrypted message, and the whisper backend id
// of the symmetric key used to decrypt the message.
// It fails if decryption of the message fails or if the message is corrupted.
func (ks *KeyStore) processSym(envelope *whisper.Envelope) (*whisper.ReceivedMessage, string, PssAddress, error) {
    metrics.GetOrRegisterCounter("pss.process.sym", nil).Inc(1)

    for i := ks.symKeyDecryptCacheCursor; i > ks.symKeyDecryptCacheCursor-cap(ks.symKeyDecryptCache) && i > 0; i-- {
        symkeyid := ks.symKeyDecryptCache[i%cap(ks.symKeyDecryptCache)]
        symkey, err := ks.w.GetSymKey(*symkeyid)
        if err != nil {
            continue
        }
        recvmsg, err := envelope.OpenSymmetric(symkey)
        if err != nil {
            continue
        }
        if !recvmsg.ValidateAndParse() {
            return nil, "", nil, errors.New("symmetrically encrypted message has invalid signature or is corrupt")
        }
        var from PssAddress
        ks.mx.RLock()
        if ks.symKeyPool[*symkeyid][Topic(envelope.Topic)] != nil {
            from = ks.symKeyPool[*symkeyid][Topic(envelope.Topic)].address
        }
        ks.mx.RUnlock()
        ks.symKeyDecryptCacheCursor++
        ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = symkeyid
        return recvmsg, *symkeyid, from, nil
    }
    return nil, "", nil, errors.New("could not decrypt message")
}

// Attempt to decrypt, validate and unpack an asymmetrically encrypted message.
// If successful, returns the unpacked whisper ReceivedMessage struct
// encapsulating the decrypted message, and the byte representation of
// the public key used to decrypt the message.
// It fails if decryption of message fails, or if the message is corrupted.
func (ks *Pss) processAsym(envelope *whisper.Envelope) (*whisper.ReceivedMessage, string, PssAddress, error) {
    metrics.GetOrRegisterCounter("pss.process.asym", nil).Inc(1)

    recvmsg, err := envelope.OpenAsymmetric(ks.privateKey)
    if err != nil {
        return nil, "", nil, fmt.Errorf("could not decrypt message: %s", err)
    }
    // check signature (if signed), strip padding
    if !recvmsg.ValidateAndParse() {
        return nil, "", nil, errors.New("invalid message")
    }
    pubkeyid := common.ToHex(crypto.FromECDSAPub(recvmsg.Src))
    var from PssAddress
    ks.mx.RLock()
    if ks.pubKeyPool[pubkeyid][Topic(envelope.Topic)] != nil {
        from = ks.pubKeyPool[pubkeyid][Topic(envelope.Topic)].address
    }
    ks.mx.RUnlock()
    return recvmsg, pubkeyid, from, nil
}

// Symkey garbage collection
// a key is removed if:
// - it is not marked as protected
// - it is not in the incoming decryption cache
func (ks *Pss) cleanKeys() (count int) {
    for keyid, peertopics := range ks.symKeyPool {
        var expiredtopics []Topic
        for topic, psp := range peertopics {
            if psp.protected {
                continue
            }

            var match bool
            for i := ks.symKeyDecryptCacheCursor; i > ks.symKeyDecryptCacheCursor-cap(ks.symKeyDecryptCache) && i > 0; i-- {
                cacheid := ks.symKeyDecryptCache[i%cap(ks.symKeyDecryptCache)]
                if *cacheid == keyid {
                    match = true
                }
            }
            if !match {
                expiredtopics = append(expiredtopics, topic)
            }
        }
        for _, topic := range expiredtopics {
            ks.mx.Lock()
            delete(ks.symKeyPool[keyid], topic)
            log.Trace("symkey cleanup deletion", "symkeyid", keyid, "topic", topic, "val", ks.symKeyPool[keyid])
            ks.mx.Unlock()
            count++
        }
    }
    return count
}

// Automatically generate a new symkey for a topic and address hint
func (ks *KeyStore) GenerateSymmetricKey(topic Topic, address PssAddress, addToCache bool) (string, error) {
    keyid, err := ks.w.GenerateSymKey()
    if err == nil {
        ks.addSymmetricKeyToPool(keyid, topic, address, addToCache, false)
    }
    return keyid, err
}

// Returns a symmetric key byte sequence stored in the whisper backend by its unique id.
// Passes on the error value from the whisper backend.
func (ks *KeyStore) GetSymmetricKey(symkeyid string) ([]byte, error) {
    return ks.w.GetSymKey(symkeyid)
}

// Links a peer symmetric key (arbitrary byte sequence) to a topic.
//
// This is required for symmetrically encrypted message exchange on the given topic.
//
// The key is stored in the whisper backend.
//
// If addtocache is set to true, the key will be added to the cache of keys
// used to attempt symmetric decryption of incoming messages.
//
// Returns a string id that can be used to retrieve the key bytes
// from the whisper backend (see pss.GetSymmetricKey())
func (ks *KeyStore) SetSymmetricKey(key []byte, topic Topic, address PssAddress, addtocache bool) (string, error) {
    if err := validateAddress(address); err != nil {
        return "", err
    }
    return ks.setSymmetricKey(key, topic, address, addtocache, true)
}

func (ks *KeyStore) setSymmetricKey(key []byte, topic Topic, address PssAddress, addtocache bool, protected bool) (string, error) {
    keyid, err := ks.w.AddSymKeyDirect(key)
    if err == nil {
        ks.addSymmetricKeyToPool(keyid, topic, address, addtocache, protected)
    }
    return keyid, err
}