forked from tw-bc-group/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileks.go
436 lines (349 loc) · 10.9 KB
/
fileks.go
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sw
import (
"bytes"
"io/ioutil"
"os"
"sync"
"errors"
"strings"
"crypto/ecdsa"
"crypto/rsa"
"encoding/hex"
"fmt"
"path/filepath"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/bccsp/utils"
)
// NewFileBasedKeyStore instantiated a file-based key store at a given position.
// The key store can be encrypted if a non-empty password is specifiec.
// It can be also be set as read only. In this case, any store operation
// will be forbidden
func NewFileBasedKeyStore(pwd []byte, path string, readOnly bool) (bccsp.KeyStore, error) {
ks := &fileBasedKeyStore{}
return ks, ks.Init(pwd, path, readOnly)
}
// fileBasedKeyStore is a folder-based KeyStore.
// Each key is stored in a separated file whose name contains the key's SKI
// and flags to identity the key's type. All the keys are stored in
// a folder whose path is provided at initialization time.
// The KeyStore can be initialized with a password, this password
// is used to encrypt and decrypt the files storing the keys.
// A KeyStore can be read only to avoid the overwriting of keys.
type fileBasedKeyStore struct {
path string
readOnly bool
isOpen bool
pwd []byte
// Sync
m sync.Mutex
}
// Init initializes this KeyStore with a password, a path to a folder
// where the keys are stored and a read only flag.
// Each key is stored in a separated file whose name contains the key's SKI
// and flags to identity the key's type.
// If the KeyStore is initialized with a password, this password
// is used to encrypt and decrypt the files storing the keys.
// The pwd can be nil for non-encrypted KeyStores. If an encrypted
// key-store is initialized without a password, then retrieving keys from the
// KeyStore will fail.
// A KeyStore can be read only to avoid the overwriting of keys.
func (ks *fileBasedKeyStore) Init(pwd []byte, path string, readOnly bool) error {
// Validate inputs
// pwd can be nil
if len(path) == 0 {
return errors.New("An invalid KeyStore path provided. Path cannot be an empty string.")
}
ks.m.Lock()
defer ks.m.Unlock()
if ks.isOpen {
return errors.New("KeyStore already initilized.")
}
ks.path = path
ks.pwd = utils.Clone(pwd)
err := ks.createKeyStoreIfNotExists()
if err != nil {
return err
}
err = ks.openKeyStore()
if err != nil {
return err
}
ks.readOnly = readOnly
return nil
}
// ReadOnly returns true if this KeyStore is read only, false otherwise.
// If ReadOnly is true then StoreKey will fail.
func (ks *fileBasedKeyStore) ReadOnly() bool {
return ks.readOnly
}
// GetKey returns a key object whose SKI is the one passed.
func (ks *fileBasedKeyStore) GetKey(ski []byte) (bccsp.Key, error) {
// Validate arguments
if len(ski) == 0 {
return nil, errors.New("Invalid SKI. Cannot be of zero length.")
}
suffix := ks.getSuffix(hex.EncodeToString(ski))
switch suffix {
case "key":
// Load the key
key, err := ks.loadKey(hex.EncodeToString(ski))
if err != nil {
return nil, fmt.Errorf("Failed loading key [%x] [%s]", ski, err)
}
return &aesPrivateKey{key, false}, nil
case "sk":
// Load the private key
key, err := ks.loadPrivateKey(hex.EncodeToString(ski))
if err != nil {
return nil, fmt.Errorf("Failed loading secret key [%x] [%s]", ski, err)
}
switch key.(type) {
case *ecdsa.PrivateKey:
return &ecdsaPrivateKey{key.(*ecdsa.PrivateKey)}, nil
case *rsa.PrivateKey:
return &rsaPrivateKey{key.(*rsa.PrivateKey)}, nil
default:
return nil, errors.New("Secret key type not recognized")
}
case "pk":
// Load the public key
key, err := ks.loadPublicKey(hex.EncodeToString(ski))
if err != nil {
return nil, fmt.Errorf("Failed loading public key [%x] [%s]", ski, err)
}
switch key.(type) {
case *ecdsa.PublicKey:
return &ecdsaPublicKey{key.(*ecdsa.PublicKey)}, nil
case *rsa.PublicKey:
return &rsaPublicKey{key.(*rsa.PublicKey)}, nil
default:
return nil, errors.New("Public key type not recognized")
}
default:
return ks.searchKeystoreForSKI(ski)
}
}
// StoreKey stores the key k in this KeyStore.
// If this KeyStore is read only then the method will fail.
func (ks *fileBasedKeyStore) StoreKey(k bccsp.Key) (err error) {
if ks.readOnly {
return errors.New("Read only KeyStore.")
}
if k == nil {
return errors.New("Invalid key. It must be different from nil.")
}
switch k.(type) {
case *ecdsaPrivateKey:
kk := k.(*ecdsaPrivateKey)
err = ks.storePrivateKey(hex.EncodeToString(k.SKI()), kk.privKey)
if err != nil {
return fmt.Errorf("Failed storing ECDSA private key [%s]", err)
}
case *ecdsaPublicKey:
kk := k.(*ecdsaPublicKey)
err = ks.storePublicKey(hex.EncodeToString(k.SKI()), kk.pubKey)
if err != nil {
return fmt.Errorf("Failed storing ECDSA public key [%s]", err)
}
case *rsaPrivateKey:
kk := k.(*rsaPrivateKey)
err = ks.storePrivateKey(hex.EncodeToString(k.SKI()), kk.privKey)
if err != nil {
return fmt.Errorf("Failed storing RSA private key [%s]", err)
}
case *rsaPublicKey:
kk := k.(*rsaPublicKey)
err = ks.storePublicKey(hex.EncodeToString(k.SKI()), kk.pubKey)
if err != nil {
return fmt.Errorf("Failed storing RSA public key [%s]", err)
}
case *aesPrivateKey:
kk := k.(*aesPrivateKey)
err = ks.storeKey(hex.EncodeToString(k.SKI()), kk.privKey)
if err != nil {
return fmt.Errorf("Failed storing AES key [%s]", err)
}
default:
return fmt.Errorf("Key type not reconigned [%s]", k)
}
return
}
func (ks *fileBasedKeyStore) searchKeystoreForSKI(ski []byte) (k bccsp.Key, err error) {
files, _ := ioutil.ReadDir(ks.path)
for _, f := range files {
if f.IsDir() {
continue
}
if f.Size() > (1 << 16) { //64k, somewhat arbitrary limit, considering even large RSA keys
continue
}
raw, err := ioutil.ReadFile(filepath.Join(ks.path, f.Name()))
if err != nil {
continue
}
key, err := utils.PEMtoPrivateKey(raw, ks.pwd)
if err != nil {
continue
}
switch key.(type) {
case *ecdsa.PrivateKey:
k = &ecdsaPrivateKey{key.(*ecdsa.PrivateKey)}
case *rsa.PrivateKey:
k = &rsaPrivateKey{key.(*rsa.PrivateKey)}
default:
continue
}
if !bytes.Equal(k.SKI(), ski) {
continue
}
return k, nil
}
return nil, fmt.Errorf("Key with SKI %s not found in %s", hex.EncodeToString(ski), ks.path)
}
func (ks *fileBasedKeyStore) getSuffix(alias string) string {
files, _ := ioutil.ReadDir(ks.path)
for _, f := range files {
if strings.HasPrefix(f.Name(), alias) {
if strings.HasSuffix(f.Name(), "sk") {
return "sk"
}
if strings.HasSuffix(f.Name(), "pk") {
return "pk"
}
if strings.HasSuffix(f.Name(), "key") {
return "key"
}
break
}
}
return ""
}
func (ks *fileBasedKeyStore) storePrivateKey(alias string, privateKey interface{}) error {
rawKey, err := utils.PrivateKeyToPEM(privateKey, ks.pwd)
if err != nil {
logger.Errorf("Failed converting private key to PEM [%s]: [%s]", alias, err)
return err
}
err = ioutil.WriteFile(ks.getPathForAlias(alias, "sk"), rawKey, 0600)
if err != nil {
logger.Errorf("Failed storing private key [%s]: [%s]", alias, err)
return err
}
return nil
}
func (ks *fileBasedKeyStore) storePublicKey(alias string, publicKey interface{}) error {
rawKey, err := utils.PublicKeyToPEM(publicKey, ks.pwd)
if err != nil {
logger.Errorf("Failed converting public key to PEM [%s]: [%s]", alias, err)
return err
}
err = ioutil.WriteFile(ks.getPathForAlias(alias, "pk"), rawKey, 0600)
if err != nil {
logger.Errorf("Failed storing private key [%s]: [%s]", alias, err)
return err
}
return nil
}
func (ks *fileBasedKeyStore) storeKey(alias string, key []byte) error {
pem, err := utils.AEStoEncryptedPEM(key, ks.pwd)
if err != nil {
logger.Errorf("Failed converting key to PEM [%s]: [%s]", alias, err)
return err
}
err = ioutil.WriteFile(ks.getPathForAlias(alias, "key"), pem, 0600)
if err != nil {
logger.Errorf("Failed storing key [%s]: [%s]", alias, err)
return err
}
return nil
}
func (ks *fileBasedKeyStore) loadPrivateKey(alias string) (interface{}, error) {
path := ks.getPathForAlias(alias, "sk")
logger.Debugf("Loading private key [%s] at [%s]...", alias, path)
raw, err := ioutil.ReadFile(path)
if err != nil {
logger.Errorf("Failed loading private key [%s]: [%s].", alias, err.Error())
return nil, err
}
privateKey, err := utils.PEMtoPrivateKey(raw, ks.pwd)
if err != nil {
logger.Errorf("Failed parsing private key [%s]: [%s].", alias, err.Error())
return nil, err
}
return privateKey, nil
}
func (ks *fileBasedKeyStore) loadPublicKey(alias string) (interface{}, error) {
path := ks.getPathForAlias(alias, "pk")
logger.Debugf("Loading public key [%s] at [%s]...", alias, path)
raw, err := ioutil.ReadFile(path)
if err != nil {
logger.Errorf("Failed loading public key [%s]: [%s].", alias, err.Error())
return nil, err
}
privateKey, err := utils.PEMtoPublicKey(raw, ks.pwd)
if err != nil {
logger.Errorf("Failed parsing private key [%s]: [%s].", alias, err.Error())
return nil, err
}
return privateKey, nil
}
func (ks *fileBasedKeyStore) loadKey(alias string) ([]byte, error) {
path := ks.getPathForAlias(alias, "key")
logger.Debugf("Loading key [%s] at [%s]...", alias, path)
pem, err := ioutil.ReadFile(path)
if err != nil {
logger.Errorf("Failed loading key [%s]: [%s].", alias, err.Error())
return nil, err
}
key, err := utils.PEMtoAES(pem, ks.pwd)
if err != nil {
logger.Errorf("Failed parsing key [%s]: [%s]", alias, err)
return nil, err
}
return key, nil
}
func (ks *fileBasedKeyStore) createKeyStoreIfNotExists() error {
// Check keystore directory
ksPath := ks.path
missing, err := utils.DirMissingOrEmpty(ksPath)
if missing {
logger.Debugf("KeyStore path [%s] missing [%t]: [%s]", ksPath, missing, utils.ErrToString(err))
err := ks.createKeyStore()
if err != nil {
logger.Errorf("Failed creating KeyStore At [%s]: [%s]", ksPath, err.Error())
return nil
}
}
return nil
}
func (ks *fileBasedKeyStore) createKeyStore() error {
// Create keystore directory root if it doesn't exist yet
ksPath := ks.path
logger.Debugf("Creating KeyStore at [%s]...", ksPath)
os.MkdirAll(ksPath, 0755)
logger.Debugf("KeyStore created at [%s].", ksPath)
return nil
}
func (ks *fileBasedKeyStore) openKeyStore() error {
if ks.isOpen {
return nil
}
ks.isOpen = true
logger.Debugf("KeyStore opened at [%s]...done", ks.path)
return nil
}
func (ks *fileBasedKeyStore) getPathForAlias(alias, suffix string) string {
return filepath.Join(ks.path, alias+"_"+suffix)
}