-
Notifications
You must be signed in to change notification settings - Fork 173
/
handler.go
347 lines (283 loc) · 9.93 KB
/
handler.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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package grpc
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"time"
errors2 "github.com/pkg/errors"
"go.uber.org/zap"
"github.com/pydio/cells/v4/common"
"github.com/pydio/cells/v4/common/crypto"
"github.com/pydio/cells/v4/common/log"
enc "github.com/pydio/cells/v4/common/proto/encryption"
"github.com/pydio/cells/v4/common/service/errors"
"github.com/pydio/cells/v4/idm/key"
)
type userKeyStore struct {
enc.UnimplementedUserKeyStoreServer
dao key.DAO
master []byte
legacy []byte
}
// NewUserKeyStore creates a master password based
func NewUserKeyStore(_ context.Context, dao key.DAO, keyring crypto.Keyring) (enc.NamedUserKeyStoreServer, error) {
masterPasswordStr, err := keyring.Get(common.ServiceGrpcNamespace_+common.ServiceUserKey, common.KeyringMasterKey)
if err != nil {
return nil, errors2.Wrap(err, "could not get master password from keyring")
}
masterPassword, err := base64.StdEncoding.DecodeString(masterPasswordStr)
if err != nil {
return nil, errors2.Wrap(err, "could not decode master password")
}
return &userKeyStore{
dao: dao,
master: masterPassword,
}, nil
}
func (ukm *userKeyStore) Name() string {
return ServiceName
}
func (ukm *userKeyStore) getDAO() key.DAO {
return ukm.dao
}
func (ukm *userKeyStore) AddKey(ctx context.Context, req *enc.AddKeyRequest) (*enc.AddKeyResponse, error) {
err := seal(req.Key, []byte(req.StrPassword))
if err != nil {
return nil, err
}
return &enc.AddKeyResponse{}, ukm.dao.SaveKey(req.Key)
}
func (ukm *userKeyStore) GetKey(ctx context.Context, req *enc.GetKeyRequest) (*enc.GetKeyResponse, error) {
rsp := &enc.GetKeyResponse{}
// TODO: Extract user / password info from Context
user := common.PydioSystemUsername
var err error
var version int
rsp.Key, version, err = ukm.dao.GetKey(user, req.KeyID)
if err != nil {
return nil, err
}
if rsp.Key == nil {
return nil, nil
}
pwd := ukm.master
if version < 4 {
if p, e := ukm.getLegacyFormat(); e == nil {
pwd = p
} else {
return nil, e
}
}
return rsp, open(rsp.Key, pwd)
}
func (ukm *userKeyStore) AdminListKeys(ctx context.Context, req *enc.AdminListKeysRequest) (*enc.AdminListKeysResponse, error) {
rsp := &enc.AdminListKeysResponse{}
var err error
rsp.Keys, err = ukm.dao.ListKeys(common.PydioSystemUsername)
return rsp, err
}
func (ukm *userKeyStore) AdminCreateKey(ctx context.Context, req *enc.AdminCreateKeyRequest) (*enc.AdminCreateKeyResponse, error) {
keyDao := ukm.getDAO()
rsp := &enc.AdminCreateKeyResponse{Success: true}
if _, _, err := keyDao.GetKey(common.PydioSystemUsername, req.KeyID); err != nil && errors.FromError(err).Code == 404 {
if er := ukm.createSystemKey(keyDao, req.KeyID, req.Label); er != nil {
return nil, er
} else {
return rsp, nil
}
} else if err != nil {
return nil, err
} else {
return nil, errors.BadRequest(common.ServiceEncKey, "Key already exists with this id!")
}
}
func (ukm *userKeyStore) AdminDeleteKey(ctx context.Context, req *enc.AdminDeleteKeyRequest) (*enc.AdminDeleteKeyResponse, error) {
return &enc.AdminDeleteKeyResponse{}, ukm.dao.DeleteKey(common.PydioSystemUsername, req.KeyID)
}
func (ukm *userKeyStore) AdminImportKey(ctx context.Context, req *enc.AdminImportKeyRequest) (*enc.AdminImportKeyResponse, error) {
var err error
log.Logger(ctx).Debug("Received request", zap.Any("Data", req))
var k *enc.Key
k, _, err = ukm.dao.GetKey(common.PydioSystemUsername, req.Key.ID)
if err != nil {
if errors.FromError(err).Code != 404 {
return nil, err
}
} else if k != nil && !req.Override {
return nil, errors.BadRequest(common.ServiceEncKey, fmt.Sprintf("Key already exists with [%s] id", req.Key.ID))
}
log.Logger(ctx).Debug("Opening sealed key with imported password")
rsp := &enc.AdminImportKeyResponse{}
err = open(req.Key, []byte(req.StrPassword))
if err != nil {
rsp.Success = false
return rsp, errors.InternalServerError(common.ServiceEncKey, "unable to decrypt %s for import, cause: %s", req.Key.ID, err.Error())
}
log.Logger(ctx).Debug("Sealing with master key")
err = seal(req.Key, ukm.master)
if err != nil {
rsp.Success = false
return rsp, errors.InternalServerError(common.ServiceEncKey, "unable to encrypt %s.%s for export, cause: %s", common.PydioSystemUsername, req.Key.ID, err.Error())
}
if req.Key.CreationDate == 0 {
if k != nil {
req.Key.CreationDate = k.CreationDate
} else {
req.Key.CreationDate = int32(time.Now().Unix())
}
}
if len(req.Key.Owner) == 0 {
req.Key.Owner = common.PydioSystemUsername
}
log.Logger(ctx).Debug("Received request", zap.Any("Data", req))
log.Logger(ctx).Debug("Adding import info")
// We set import info
if req.Key.Info == nil {
req.Key.Info = &enc.KeyInfo{}
}
if req.Key.Info.Imports == nil {
req.Key.Info.Imports = []*enc.Import{}
}
req.Key.Info.Imports = append(req.Key.Info.Imports, &enc.Import{
By: common.PydioSystemUsername,
Date: int32(time.Now().Unix()),
})
log.Logger(ctx).Debug("Saving new key")
err = ukm.dao.SaveKey(req.Key)
if err != nil {
rsp.Success = false
return rsp, errors.InternalServerError(common.ServiceEncKey, "failed to save imported key, cause: %s", err.Error())
}
log.Logger(ctx).Debug("Returning response")
rsp.Success = true
return rsp, nil
}
func (ukm *userKeyStore) AdminExportKey(ctx context.Context, req *enc.AdminExportKeyRequest) (*enc.AdminExportKeyResponse, error) {
//Get key from dao
var err error
rsp := &enc.AdminExportKeyResponse{}
var version int
rsp.Key, version, err = ukm.dao.GetKey(common.PydioSystemUsername, req.KeyID)
if err != nil {
return rsp, err
}
log.Logger(ctx).Debug(fmt.Sprintf("Exporting key %s", rsp.Key.Content))
// We set export info
if rsp.Key.Info.Exports == nil {
rsp.Key.Info.Exports = []*enc.Export{}
}
rsp.Key.Info.Exports = append(rsp.Key.Info.Exports, &enc.Export{
By: common.PydioSystemUsername,
Date: int32(time.Now().Unix()),
})
// We update the key
err = ukm.dao.SaveKey(rsp.Key, version)
if err != nil {
return rsp, errors.InternalServerError(common.ServiceEncKey, "failed to update key info, cause: %s", err.Error())
}
pwd := ukm.master
if version < 4 {
if p, e := ukm.getLegacyFormat(); e == nil {
pwd = p
} else {
return nil, e
}
}
err = open(rsp.Key, pwd)
if err != nil {
return rsp, errors.InternalServerError(common.ServiceEncKey, "unable to decrypt for %s with key %s, cause: %s", common.PydioSystemUsername, req.KeyID, err)
}
err = seal(rsp.Key, []byte(req.StrPassword))
if err != nil {
return rsp, errors.InternalServerError(common.ServiceEncKey, "unable to encrypt for %s with key %s for export, cause: %s", common.PydioSystemUsername, req.KeyID, err)
}
return rsp, nil
}
// Create a default key or create a system key with a given ID
func (ukm *userKeyStore) createSystemKey(dao key.DAO, keyID string, keyLabel string) error {
systemKey := &enc.Key{
ID: keyID,
Owner: common.PydioSystemUsername,
Label: keyLabel,
CreationDate: int32(time.Now().Unix()),
}
keyContentBytes := make([]byte, 32)
_, err := rand.Read(keyContentBytes)
if err != nil {
return err
}
masterKey := crypto.KeyFromPassword(ukm.master, 32)
encryptedKeyContentBytes, err := crypto.Seal(masterKey, keyContentBytes)
if err != nil {
return errors.InternalServerError(common.ServiceEncKey, "failed to encrypt the default key. Cause: %s", err.Error())
}
systemKey.Content = base64.StdEncoding.EncodeToString(encryptedKeyContentBytes)
log.Logger(context.Background()).Debug(fmt.Sprintf("Saving default key %s", systemKey.Content))
return dao.SaveKey(systemKey)
}
func (ukm *userKeyStore) getLegacyFormat() ([]byte, error) {
if len(ukm.legacy) == 0 {
// Ensure that the master password is correctly encoded
s, err := json.Marshal(map[string]string{
"master": string(ukm.master),
})
if err != nil {
return nil, fmt.Errorf("error marshalling key %v", err)
}
var mm map[string]string
if err := json.Unmarshal(s, &mm); err != nil {
return nil, fmt.Errorf("error unmarshalling key %v", err)
}
ukm.legacy = []byte(mm["master"])
}
return ukm.legacy, nil
}
func seal(k *enc.Key, passwordBytes []byte) error {
keyContentBytes, err := base64.StdEncoding.DecodeString(k.Content)
if err != nil {
return errors.New(common.ServiceUserKey, "unable to decode key", 400)
}
passwordKey := crypto.KeyFromPassword(passwordBytes, 32)
encryptedKeyContentBytes, err := crypto.Seal(passwordKey, keyContentBytes)
if err != nil {
return errors.InternalServerError(common.ServiceEncKey, "failed to encrypt the default key, cause: %s", err.Error())
}
k.Content = base64.StdEncoding.EncodeToString(encryptedKeyContentBytes)
return nil
}
func open(k *enc.Key, passwordBytes []byte) error {
sealedContentBytes, err := base64.StdEncoding.DecodeString(k.Content)
if err != nil {
return errors.New(common.ServiceUserKey, "unable to decode key", 400)
}
passwordKey := crypto.KeyFromPassword(passwordBytes, 32)
nonce := sealedContentBytes[:12]
keySealContentBytes := sealedContentBytes[12:]
keyPlainContentBytes, err := crypto.Open(passwordKey, nonce, keySealContentBytes)
if err != nil {
return err
}
k.Content = base64.StdEncoding.EncodeToString(keyPlainContentBytes)
return nil
}