-
Notifications
You must be signed in to change notification settings - Fork 672
/
keystore.go
392 lines (322 loc) · 9.75 KB
/
keystore.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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package keystore
import (
"errors"
"fmt"
"net/http"
"sync"
"github.com/gorilla/rpc/v2"
"github.com/ava-labs/avalanchego/chains/atomic"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/encdb"
"github.com/ava-labs/avalanchego/database/manager"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/password"
jsoncodec "github.com/ava-labs/avalanchego/utils/json"
)
const (
// maxUserLen is the maximum allowed length of a username
maxUserLen = 1024
)
var (
errEmptyUsername = errors.New("empty username")
errUserMaxLength = fmt.Errorf("username exceeds maximum length of %d chars", maxUserLen)
usersPrefix = []byte("users")
bcsPrefix = []byte("bcs")
migratedKey = []byte("migrated")
_ Keystore = &keystore{}
)
type Keystore interface {
// Create the API endpoint for this keystore.
CreateHandler() (http.Handler, error)
// NewBlockchainKeyStore returns this keystore limiting the functionality to
// a single blockchain database.
NewBlockchainKeyStore(blockchainID ids.ID) BlockchainKeystore
// Get a database that is able to read and write unencrypted values from the
// underlying database.
GetDatabase(bID ids.ID, username, password string) (*encdb.Database, error)
// Get the underlying database that is able to read and write encrypted
// values. This Database will not perform any encrypting or decrypting of
// values and is not recommended to be used when implementing a VM.
GetRawDatabase(bID ids.ID, username, password string) (database.Database, error)
// CreateUser attempts to register this username and password as a new user
// of the keystore.
CreateUser(username, pw string) error
// DeleteUser attempts to remove the provided username and all of its data
// from the keystore.
DeleteUser(username, pw string) error
// ListUsers returns all the users that currently exist in this keystore.
ListUsers() ([]string, error)
// ImportUser imports a serialized encoding of a user's information complete
// with encrypted database values. The password is integrity checked.
ImportUser(username, pw string, user []byte) error
// ExportUser exports a serialized encoding of a user's information complete
// with encrypted database values.
ExportUser(username, pw string) ([]byte, error)
// Get the password that is used by [username]. If [username] doesn't exist,
// no error is returned and a nil password hash is returned.
getPassword(username string) (*password.Hash, error)
}
type kvPair struct {
Key []byte `serialize:"true"`
Value []byte `serialize:"true"`
}
// user describes the full content of a user
type user struct {
password.Hash `serialize:"true"`
Data []kvPair `serialize:"true"`
}
// keystore implements keystore management logic
type keystore struct {
lock sync.Mutex
log logging.Logger
// Key: username
// Value: The hash of that user's password
usernameToPassword map[string]*password.Hash
// Used to persist users and their data
userDB database.Database
bcDB database.Database
// BaseDB
// / \
// UserDB BlockchainDB
// / | \
// Usr Usr Usr
// / | \
// BID BID BID
}
func New(log logging.Logger, dbManager manager.Manager) (Keystore, error) {
currentDB := dbManager.Current()
keystore := &keystore{
log: log,
usernameToPassword: make(map[string]*password.Hash),
userDB: prefixdb.New(usersPrefix, currentDB.Database),
bcDB: prefixdb.New(bcsPrefix, currentDB.Database),
}
return keystore, keystore.migrate(dbManager)
}
func (ks *keystore) CreateHandler() (http.Handler, error) {
newServer := rpc.NewServer()
codec := jsoncodec.NewCodec()
newServer.RegisterCodec(codec, "application/json")
newServer.RegisterCodec(codec, "application/json;charset=UTF-8")
if err := newServer.RegisterService(&service{ks: ks}, "keystore"); err != nil {
return nil, err
}
return newServer, nil
}
func (ks *keystore) NewBlockchainKeyStore(blockchainID ids.ID) BlockchainKeystore {
return &blockchainKeystore{
blockchainID: blockchainID,
ks: ks,
}
}
func (ks *keystore) GetDatabase(bID ids.ID, username, password string) (*encdb.Database, error) {
bcDB, err := ks.GetRawDatabase(bID, username, password)
if err != nil {
return nil, err
}
return encdb.New([]byte(password), bcDB)
}
func (ks *keystore) GetRawDatabase(bID ids.ID, username, pw string) (database.Database, error) {
if username == "" {
return nil, errEmptyUsername
}
ks.lock.Lock()
defer ks.lock.Unlock()
passwordHash, err := ks.getPassword(username)
if err != nil {
return nil, err
}
if passwordHash == nil || !passwordHash.Check(pw) {
return nil, fmt.Errorf("incorrect password for user %q", username)
}
userDB := prefixdb.New([]byte(username), ks.bcDB)
bcDB := prefixdb.NewNested(bID[:], userDB)
return bcDB, nil
}
func (ks *keystore) CreateUser(username, pw string) error {
if username == "" {
return errEmptyUsername
}
if len(username) > maxUserLen {
return errUserMaxLength
}
ks.lock.Lock()
defer ks.lock.Unlock()
passwordHash, err := ks.getPassword(username)
if err != nil {
return err
}
if passwordHash != nil {
return fmt.Errorf("user already exists: %s", username)
}
if err := password.IsValid(pw, password.OK); err != nil {
return err
}
passwordHash = &password.Hash{}
if err := passwordHash.Set(pw); err != nil {
return err
}
passwordBytes, err := c.Marshal(codecVersion, passwordHash)
if err != nil {
return err
}
if err := ks.userDB.Put([]byte(username), passwordBytes); err != nil {
return err
}
ks.usernameToPassword[username] = passwordHash
return nil
}
func (ks *keystore) DeleteUser(username, pw string) error {
if username == "" {
return errEmptyUsername
}
if len(username) > maxUserLen {
return errUserMaxLength
}
ks.lock.Lock()
defer ks.lock.Unlock()
// check if user exists and valid user.
passwordHash, err := ks.getPassword(username)
switch {
case err != nil:
return err
case passwordHash == nil:
return fmt.Errorf("user doesn't exist: %s", username)
case !passwordHash.Check(pw):
return fmt.Errorf("incorrect password for user %q", username)
}
userNameBytes := []byte(username)
userBatch := ks.userDB.NewBatch()
if err := userBatch.Delete(userNameBytes); err != nil {
return err
}
userDataDB := prefixdb.New(userNameBytes, ks.bcDB)
dataBatch := userDataDB.NewBatch()
it := userDataDB.NewIterator()
defer it.Release()
for it.Next() {
if err = dataBatch.Delete(it.Key()); err != nil {
return err
}
}
if err = it.Error(); err != nil {
return err
}
if err := atomic.WriteAll(dataBatch, userBatch); err != nil {
return err
}
// delete from users map.
delete(ks.usernameToPassword, username)
return nil
}
func (ks *keystore) ListUsers() ([]string, error) {
users := []string{}
ks.lock.Lock()
defer ks.lock.Unlock()
it := ks.userDB.NewIterator()
defer it.Release()
for it.Next() {
users = append(users, string(it.Key()))
}
return users, it.Error()
}
func (ks *keystore) ImportUser(username, pw string, userBytes []byte) error {
if username == "" {
return errEmptyUsername
}
if len(username) > maxUserLen {
return errUserMaxLength
}
ks.lock.Lock()
defer ks.lock.Unlock()
passwordHash, err := ks.getPassword(username)
if err != nil {
return err
}
if passwordHash != nil {
return fmt.Errorf("user already exists: %s", username)
}
userData := user{}
if _, err := c.Unmarshal(userBytes, &userData); err != nil {
return err
}
if !userData.Hash.Check(pw) {
return fmt.Errorf("incorrect password for user %q", username)
}
usrBytes, err := c.Marshal(codecVersion, &userData.Hash)
if err != nil {
return err
}
userBatch := ks.userDB.NewBatch()
if err := userBatch.Put([]byte(username), usrBytes); err != nil {
return err
}
userDataDB := prefixdb.New([]byte(username), ks.bcDB)
dataBatch := userDataDB.NewBatch()
for _, kvp := range userData.Data {
if err := dataBatch.Put(kvp.Key, kvp.Value); err != nil {
return fmt.Errorf("error on database put: %w", err)
}
}
if err := atomic.WriteAll(dataBatch, userBatch); err != nil {
return err
}
ks.usernameToPassword[username] = &userData.Hash
return nil
}
func (ks *keystore) ExportUser(username, pw string) ([]byte, error) {
if username == "" {
return nil, errEmptyUsername
}
if len(username) > maxUserLen {
return nil, errUserMaxLength
}
ks.lock.Lock()
defer ks.lock.Unlock()
passwordHash, err := ks.getPassword(username)
if err != nil {
return nil, err
}
if passwordHash == nil || !passwordHash.Check(pw) {
return nil, fmt.Errorf("incorrect password for user %q", username)
}
userDB := prefixdb.New([]byte(username), ks.bcDB)
userData := user{Hash: *passwordHash}
it := userDB.NewIterator()
defer it.Release()
for it.Next() {
userData.Data = append(userData.Data, kvPair{
Key: it.Key(),
Value: it.Value(),
})
}
if err := it.Error(); err != nil {
return nil, err
}
// Return the byte representation of the user
return c.Marshal(codecVersion, &userData)
}
func (ks *keystore) getPassword(username string) (*password.Hash, error) {
// If the user is already in memory, return it
passwordHash, exists := ks.usernameToPassword[username]
if exists {
return passwordHash, nil
}
// The user is not in memory; try the database
userBytes, err := ks.userDB.Get([]byte(username))
if err == database.ErrNotFound {
// The user doesn't exist
return nil, nil
}
if err != nil {
// An unexpected database error occurred
return nil, err
}
passwordHash = &password.Hash{}
_, err = c.Unmarshal(userBytes, passwordHash)
return passwordHash, err
}