github.com/codingfuture/orig-energi3@v0.8.4/swarm/pss/keystore.go (about) 1 // Copyright 2019 The Energi Core Authors 2 // Copyright 2018 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 package pss 19 20 import ( 21 "crypto/ecdsa" 22 "errors" 23 "fmt" 24 "sync" 25 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/crypto" 28 "github.com/ethereum/go-ethereum/metrics" 29 "github.com/ethereum/go-ethereum/swarm/log" 30 whisper "github.com/ethereum/go-ethereum/whisper/whisperv6" 31 ) 32 33 type KeyStore struct { 34 w *whisper.Whisper // key and encryption backend 35 36 mx sync.RWMutex 37 pubKeyPool map[string]map[Topic]*pssPeer // mapping of hex public keys to peer address by topic. 38 symKeyPool map[string]map[Topic]*pssPeer // mapping of symkeyids to peer address by topic. 39 symKeyDecryptCache []*string // fast lookup of symkeys recently used for decryption; last used is on top of stack 40 symKeyDecryptCacheCursor int // modular cursor pointing to last used, wraps on symKeyDecryptCache array 41 } 42 43 func loadKeyStore() *KeyStore { 44 return &KeyStore{ 45 w: whisper.New(&whisper.DefaultConfig), 46 47 pubKeyPool: make(map[string]map[Topic]*pssPeer), 48 symKeyPool: make(map[string]map[Topic]*pssPeer), 49 symKeyDecryptCache: make([]*string, defaultSymKeyCacheCapacity), 50 } 51 } 52 53 func (ks *KeyStore) isSymKeyStored(key string) bool { 54 ks.mx.RLock() 55 defer ks.mx.RUnlock() 56 var ok bool 57 _, ok = ks.symKeyPool[key] 58 return ok 59 } 60 61 func (ks *KeyStore) isPubKeyStored(key string) bool { 62 ks.mx.RLock() 63 defer ks.mx.RUnlock() 64 var ok bool 65 _, ok = ks.pubKeyPool[key] 66 return ok 67 } 68 69 func (ks *KeyStore) getPeerSym(symkeyid string, topic Topic) (*pssPeer, bool) { 70 ks.mx.RLock() 71 defer ks.mx.RUnlock() 72 psp, ok := ks.symKeyPool[symkeyid][topic] 73 return psp, ok 74 } 75 76 func (ks *KeyStore) getPeerPub(pubkeyid string, topic Topic) (*pssPeer, bool) { 77 ks.mx.RLock() 78 defer ks.mx.RUnlock() 79 psp, ok := ks.pubKeyPool[pubkeyid][topic] 80 return psp, ok 81 } 82 83 // Links a peer ECDSA public key to a topic. 84 // This is required for asymmetric message exchange on the given topic. 85 // The value in `address` will be used as a routing hint for the public key / topic association. 86 func (ks *KeyStore) SetPeerPublicKey(pubkey *ecdsa.PublicKey, topic Topic, address PssAddress) error { 87 if err := validateAddress(address); err != nil { 88 return err 89 } 90 pubkeybytes := crypto.FromECDSAPub(pubkey) 91 if len(pubkeybytes) == 0 { 92 return fmt.Errorf("invalid public key: %v", pubkey) 93 } 94 pubkeyid := common.ToHex(pubkeybytes) 95 psp := &pssPeer{ 96 address: address, 97 } 98 ks.mx.Lock() 99 if _, ok := ks.pubKeyPool[pubkeyid]; !ok { 100 ks.pubKeyPool[pubkeyid] = make(map[Topic]*pssPeer) 101 } 102 ks.pubKeyPool[pubkeyid][topic] = psp 103 ks.mx.Unlock() 104 log.Trace("added pubkey", "pubkeyid", pubkeyid, "topic", topic, "address", address) 105 return nil 106 } 107 108 // adds a symmetric key to the pss key pool, and optionally adds the key to the 109 // collection of keys used to attempt symmetric decryption of incoming messages 110 func (ks *KeyStore) addSymmetricKeyToPool(keyid string, topic Topic, address PssAddress, addtocache bool, protected bool) { 111 psp := &pssPeer{ 112 address: address, 113 protected: protected, 114 } 115 ks.mx.Lock() 116 if _, ok := ks.symKeyPool[keyid]; !ok { 117 ks.symKeyPool[keyid] = make(map[Topic]*pssPeer) 118 } 119 ks.symKeyPool[keyid][topic] = psp 120 ks.mx.Unlock() 121 if addtocache { 122 ks.symKeyDecryptCacheCursor++ 123 ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = &keyid 124 } 125 } 126 127 // Returns all recorded topic and address combination for a specific public key 128 func (ks *KeyStore) GetPublickeyPeers(keyid string) (topic []Topic, address []PssAddress, err error) { 129 ks.mx.RLock() 130 defer ks.mx.RUnlock() 131 for t, peer := range ks.pubKeyPool[keyid] { 132 topic = append(topic, t) 133 address = append(address, peer.address) 134 } 135 return topic, address, nil 136 } 137 138 func (ks *KeyStore) getPeerAddress(keyid string, topic Topic) (PssAddress, error) { 139 ks.mx.RLock() 140 defer ks.mx.RUnlock() 141 if peers, ok := ks.pubKeyPool[keyid]; ok { 142 if t, ok := peers[topic]; ok { 143 return t.address, nil 144 } 145 } 146 return nil, fmt.Errorf("peer with pubkey %s, topic %x not found", keyid, topic) 147 } 148 149 // Attempt to decrypt, validate and unpack a symmetrically encrypted message. 150 // If successful, returns the unpacked whisper ReceivedMessage struct 151 // encapsulating the decrypted message, and the whisper backend id 152 // of the symmetric key used to decrypt the message. 153 // It fails if decryption of the message fails or if the message is corrupted. 154 func (ks *KeyStore) processSym(envelope *whisper.Envelope) (*whisper.ReceivedMessage, string, PssAddress, error) { 155 metrics.GetOrRegisterCounter("pss.process.sym", nil).Inc(1) 156 157 for i := ks.symKeyDecryptCacheCursor; i > ks.symKeyDecryptCacheCursor-cap(ks.symKeyDecryptCache) && i > 0; i-- { 158 symkeyid := ks.symKeyDecryptCache[i%cap(ks.symKeyDecryptCache)] 159 symkey, err := ks.w.GetSymKey(*symkeyid) 160 if err != nil { 161 continue 162 } 163 recvmsg, err := envelope.OpenSymmetric(symkey) 164 if err != nil { 165 continue 166 } 167 if !recvmsg.ValidateAndParse() { 168 return nil, "", nil, errors.New("symmetrically encrypted message has invalid signature or is corrupt") 169 } 170 var from PssAddress 171 ks.mx.RLock() 172 if ks.symKeyPool[*symkeyid][Topic(envelope.Topic)] != nil { 173 from = ks.symKeyPool[*symkeyid][Topic(envelope.Topic)].address 174 } 175 ks.mx.RUnlock() 176 ks.symKeyDecryptCacheCursor++ 177 ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = symkeyid 178 return recvmsg, *symkeyid, from, nil 179 } 180 return nil, "", nil, errors.New("could not decrypt message") 181 } 182 183 // Attempt to decrypt, validate and unpack an asymmetrically encrypted message. 184 // If successful, returns the unpacked whisper ReceivedMessage struct 185 // encapsulating the decrypted message, and the byte representation of 186 // the public key used to decrypt the message. 187 // It fails if decryption of message fails, or if the message is corrupted. 188 func (ks *Pss) processAsym(envelope *whisper.Envelope) (*whisper.ReceivedMessage, string, PssAddress, error) { 189 metrics.GetOrRegisterCounter("pss.process.asym", nil).Inc(1) 190 191 recvmsg, err := envelope.OpenAsymmetric(ks.privateKey) 192 if err != nil { 193 return nil, "", nil, fmt.Errorf("could not decrypt message: %s", err) 194 } 195 // check signature (if signed), strip padding 196 if !recvmsg.ValidateAndParse() { 197 return nil, "", nil, errors.New("invalid message") 198 } 199 pubkeyid := common.ToHex(crypto.FromECDSAPub(recvmsg.Src)) 200 var from PssAddress 201 ks.mx.RLock() 202 if ks.pubKeyPool[pubkeyid][Topic(envelope.Topic)] != nil { 203 from = ks.pubKeyPool[pubkeyid][Topic(envelope.Topic)].address 204 } 205 ks.mx.RUnlock() 206 return recvmsg, pubkeyid, from, nil 207 } 208 209 // Symkey garbage collection 210 // a key is removed if: 211 // - it is not marked as protected 212 // - it is not in the incoming decryption cache 213 func (ks *Pss) cleanKeys() (count int) { 214 for keyid, peertopics := range ks.symKeyPool { 215 var expiredtopics []Topic 216 for topic, psp := range peertopics { 217 if psp.protected { 218 continue 219 } 220 221 var match bool 222 for i := ks.symKeyDecryptCacheCursor; i > ks.symKeyDecryptCacheCursor-cap(ks.symKeyDecryptCache) && i > 0; i-- { 223 cacheid := ks.symKeyDecryptCache[i%cap(ks.symKeyDecryptCache)] 224 if *cacheid == keyid { 225 match = true 226 } 227 } 228 if !match { 229 expiredtopics = append(expiredtopics, topic) 230 } 231 } 232 for _, topic := range expiredtopics { 233 ks.mx.Lock() 234 delete(ks.symKeyPool[keyid], topic) 235 log.Trace("symkey cleanup deletion", "symkeyid", keyid, "topic", topic, "val", ks.symKeyPool[keyid]) 236 ks.mx.Unlock() 237 count++ 238 } 239 } 240 return count 241 } 242 243 // Automatically generate a new symkey for a topic and address hint 244 func (ks *KeyStore) GenerateSymmetricKey(topic Topic, address PssAddress, addToCache bool) (string, error) { 245 keyid, err := ks.w.GenerateSymKey() 246 if err == nil { 247 ks.addSymmetricKeyToPool(keyid, topic, address, addToCache, false) 248 } 249 return keyid, err 250 } 251 252 // Returns a symmetric key byte sequence stored in the whisper backend by its unique id. 253 // Passes on the error value from the whisper backend. 254 func (ks *KeyStore) GetSymmetricKey(symkeyid string) ([]byte, error) { 255 return ks.w.GetSymKey(symkeyid) 256 } 257 258 // Links a peer symmetric key (arbitrary byte sequence) to a topic. 259 // 260 // This is required for symmetrically encrypted message exchange on the given topic. 261 // 262 // The key is stored in the whisper backend. 263 // 264 // If addtocache is set to true, the key will be added to the cache of keys 265 // used to attempt symmetric decryption of incoming messages. 266 // 267 // Returns a string id that can be used to retrieve the key bytes 268 // from the whisper backend (see pss.GetSymmetricKey()) 269 func (ks *KeyStore) SetSymmetricKey(key []byte, topic Topic, address PssAddress, addtocache bool) (string, error) { 270 if err := validateAddress(address); err != nil { 271 return "", err 272 } 273 return ks.setSymmetricKey(key, topic, address, addtocache, true) 274 } 275 276 func (ks *KeyStore) setSymmetricKey(key []byte, topic Topic, address PssAddress, addtocache bool, protected bool) (string, error) { 277 keyid, err := ks.w.AddSymKeyDirect(key) 278 if err == nil { 279 ks.addSymmetricKeyToPool(keyid, topic, address, addtocache, protected) 280 } 281 return keyid, err 282 }