-
Notifications
You must be signed in to change notification settings - Fork 180
/
handler-encryption.go
771 lines (669 loc) · 25.1 KB
/
handler-encryption.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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*
* 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 views
import (
"context"
"fmt"
"io"
"strings"
"github.com/micro/go-micro/errors"
"github.com/pborman/uuid"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/crypto"
"github.com/pydio/cells/common/log"
defaults "github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/encryption"
"github.com/pydio/cells/common/proto/object"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/idm/key"
"github.com/pydio/minio-go"
)
//EncryptionHandler encryption node middleware
type EncryptionHandler struct {
AbstractHandler
userKeyTool key.UserKeyTool
nodeKeyManagerClient encryption.NodeKeyManagerClient
}
func (e *EncryptionHandler) SetUserKeyTool(keyTool key.UserKeyTool) {
e.userKeyTool = keyTool
}
func (e *EncryptionHandler) SetNodeKeyManagerClient(nodeKeyManagerClient encryption.NodeKeyManagerClient) {
e.nodeKeyManagerClient = nodeKeyManagerClient
}
//GetObject enriches request metadata for GetObject with Encryption Materials, if required by the datasource.
func (e *EncryptionHandler) GetObject(ctx context.Context, node *tree.Node, requestData *GetRequestData) (io.ReadCloser, error) {
if strings.HasSuffix(node.Path, common.PYDIO_SYNC_HIDDEN_FILE_META) {
return e.next.GetObject(ctx, node, requestData)
}
branchInfo, ok := GetBranchInfo(ctx, "in")
if !ok || branchInfo.EncryptionMode != object.EncryptionMode_MASTER {
return e.next.GetObject(ctx, node, requestData)
}
clone := node.Clone()
if len(node.Uuid) == 0 || node.Size == 0 {
rsp, readErr := e.next.ReadNode(ctx, &tree.ReadNodeRequest{
Node: node,
})
if readErr != nil {
return nil, errors.NotFound("views.Handler.encryption", "failed to get node UUID: %s", readErr)
}
clone.Uuid = rsp.Node.Uuid
clone.Size = rsp.Node.Size
}
if len(clone.Uuid) == 0 || clone.Size == 0 {
return nil, errors.NotFound("views.handler.encryption.GetObject", "node Uuid and size are both required")
}
dsName := clone.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
if dsName == "" {
if branchInfo.Root != nil {
dsName = branchInfo.Root.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
} else if branchInfo.Name != "" {
dsName = branchInfo.Name
} else {
return nil, errors.New("views.handler.encryption.GetObject", "cannot find datasource name", 500)
}
clone.SetMeta(common.META_NAMESPACE_DATASOURCE_NAME, dsName)
}
info, offset, length, skipBytesCount, err := e.getNodeInfoForRead(ctx, clone, requestData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.GetObject: failed to get node info", zap.Error(err))
return nil, err
}
if offset == 0 && length == 0 {
length = -1
}
keyProtectionTool, err := e.getKeyProtectionTool(ctx)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.GetObject: failed to load key tool", zap.Error(err))
return nil, err
}
plainKey, err := keyProtectionTool.GetDecrypted(ctx, branchInfo.EncryptionKey, info.NodeKey.KeyData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.GetObject: failed to decrypt materials key", zap.String("user", dsName), zap.Error(err))
return nil, err
}
boundariesOk := requestData.StartOffset >= 0 && requestData.StartOffset <= clone.Size
boundariesOk = boundariesOk && (requestData.Length == -1 || requestData.Length > 0 && requestData.StartOffset+requestData.Length <= clone.Size)
if !boundariesOk {
return nil, errors.New("views.handler.encryption.GetObject", "wrong range", 400)
}
fullRead := requestData.StartOffset == 0 && (requestData.Length <= 0 || requestData.Length == clone.Size)
if requestData.Length <= 0 {
requestData.Length = clone.Size
}
if info.Node.Legacy {
eMat := crypto.NewLegacyAESGCMMaterials(info)
rangeRequestData := &GetRequestData{VersionId: requestData.VersionId, StartOffset: 0, Length: -1}
if !fullRead {
err = eMat.SetPlainRange(requestData.StartOffset, requestData.Length)
if err != nil {
return nil, err
}
rangeRequestData.StartOffset, rangeRequestData.Length = eMat.CalculateEncryptedRange(clone.Size)
}
reader, err := e.next.GetObject(ctx, clone, rangeRequestData)
if err != nil {
return nil, err
}
return eMat, eMat.SetupDecryptMode(plainKey, reader)
} else {
eMat := crypto.NewAESGCMMaterials(info, nil)
if !fullRead {
eMat.SetPlainRange(skipBytesCount, requestData.Length)
}
rangeRequestData := &GetRequestData{
StartOffset: offset,
Length: length,
VersionId: requestData.VersionId,
}
reader, err := e.next.GetObject(ctx, clone, rangeRequestData)
if err != nil {
return nil, err
}
return eMat, eMat.SetupDecryptMode(plainKey, reader)
}
}
// PutObject enriches request metadata for PutObject with Encryption Materials, if required by datasource.
func (e *EncryptionHandler) PutObject(ctx context.Context, node *tree.Node, reader io.Reader, requestData *PutRequestData) (int64, error) {
if strings.HasSuffix(node.Path, common.PYDIO_SYNC_HIDDEN_FILE_META) {
return e.next.PutObject(ctx, node, reader, requestData)
}
branchInfo, ok := GetBranchInfo(ctx, "in")
var err error
if !ok || branchInfo.EncryptionMode != object.EncryptionMode_MASTER {
return e.next.PutObject(ctx, node, reader, requestData)
}
clone := node.Clone()
if len(clone.Uuid) == 0 {
rsp, readErr := e.next.ReadNode(ctx, &tree.ReadNodeRequest{
Node: node,
})
if readErr != nil {
return -1, errors.NotFound("views.handler.encryption.PutObject", "failed to get node UUID: %s", readErr)
}
if len(rsp.Node.Uuid) == 0 {
return -1, errors.NotFound("views.handler.encryption.PutObject", "failed to get node UUID")
}
clone.Uuid = rsp.Node.Uuid
}
dsName := clone.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
if dsName == "" {
_ = clone.SetMeta(common.META_NAMESPACE_DATASOURCE_NAME, branchInfo.Name)
}
keyProtectionTool, err := e.getKeyProtectionTool(ctx)
if err != nil {
return 0, err
}
streamClient, err := e.getNodeKeyManagerClient().SetNodeInfo(ctx)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to save node encryption info", zap.Error(err))
return 0, err
}
streamer := &setBlockStream{
client: streamClient,
nodeUuid: clone.Uuid,
keySent: false,
ctx: ctx,
}
var encryptionKeyPlainBytes []byte
info, err := e.getNodeInfoForWrite(ctx, clone)
if err != nil {
if errors.Parse(err.Error()).Code != 404 {
return 0, err
}
info, err = e.createNodeInfo(ctx, clone)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to create node info", zap.Error(err))
return 0, err
}
encryptionKeyPlainBytes = info.NodeKey.KeyData
info.NodeKey.KeyData, err = keyProtectionTool.GetEncrypted(ctx, branchInfo.EncryptionKey, info.NodeKey.KeyData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to encrypt node key", zap.Error(err))
return 0, err
}
err = streamer.SendKey(info.NodeKey)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to set nodeKey", zap.Error(err))
return 0, err
}
} else {
encryptionKeyPlainBytes, err = keyProtectionTool.GetDecrypted(ctx, branchInfo.EncryptionKey, info.NodeKey.KeyData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to decrypt key", zap.Error(err))
return 0, err
}
err = streamer.ClearBlocks(clone.Uuid)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.PutObject: failed to clear old blocks", zap.Error(err))
return 0, err
}
}
encryptionMaterials := crypto.NewAESGCMMaterials(info, streamer)
if err := encryptionMaterials.SetupEncryptMode(encryptionKeyPlainBytes, reader); err != nil {
return 0, err
}
requestData.Md5Sum = nil
requestData.Sha256Sum = nil
// Update Size : set Plain as Meta and Encrypted as Size.
if requestData.Metadata == nil {
requestData.Metadata = make(map[string]string, 1)
}
if requestData.Size > -1 {
log.Logger(ctx).Debug("Adding special header to store clear size", zap.Any("s", requestData.Size))
requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE] = fmt.Sprintf("%d", requestData.Size)
} else {
requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE] = common.X_AMZ_META_CLEAR_SIZE_UNKOWN
}
requestData.Size = encryptionMaterials.CalculateOutputSize(requestData.Size, info.NodeKey.OwnerId)
n, err := e.next.PutObject(ctx, node, encryptionMaterials, requestData)
return n, err
}
// CopyObject enriches request metadata for CopyObject with Encryption Materials, if required by the datasource
func (e *EncryptionHandler) CopyObject(ctx context.Context, from *tree.Node, to *tree.Node, requestData *CopyRequestData) (int64, error) {
srcInfo, ok2 := GetBranchInfo(ctx, "from")
destInfo, ok := GetBranchInfo(ctx, "to")
if !ok || !ok2 {
return 0, errors.InternalServerError("views.handler.encryption.CopyObject", "Cannot find Client for src or dest")
}
readCtx := WithBranchInfo(ctx, "in", srcInfo, true)
writeCtx := WithBranchInfo(ctx, "in", destInfo, true)
// Ds are not encrypted, let if flow
if srcInfo.EncryptionMode != object.EncryptionMode_MASTER && destInfo.EncryptionMode != object.EncryptionMode_MASTER {
return e.next.CopyObject(ctx, from, to, requestData)
}
// Move
var move, sameClient bool
if d, ok := requestData.Metadata[common.X_AMZ_META_DIRECTIVE]; ok && d == "COPY" {
move = true
}
sameClient = destInfo.Client == srcInfo.Client
if move && sameClient {
return e.next.CopyObject(ctx, from, to, requestData)
}
cloneFrom := from.Clone()
cloneTo := to.Clone()
if sameClient {
if len(cloneFrom.Uuid) == 0 {
rsp, readErr := e.next.ReadNode(readCtx, &tree.ReadNodeRequest{
Node: from,
})
if readErr != nil {
return -1, errors.NotFound("views.handler.encryption.CopyObject", "failed to get node UUID: %s", readErr)
}
if len(rsp.Node.Uuid) == 0 {
return -1, errors.NotFound("views.handler.encryption.CopyObject", "failed to get node UUID")
}
cloneFrom.Uuid = rsp.Node.Uuid
}
// Force target Uuid to copy encryption material
cloneTo.Uuid = uuid.New()
// Just add the metadata and let underlying handler do the job
requestData.Metadata[common.X_AMZ_META_NODE_UUID] = cloneTo.Uuid
requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE] = fmt.Sprintf("%d", cloneFrom.Size)
l, er := e.next.CopyObject(ctx, from, to, requestData)
if er == nil {
err := e.copyNodeEncryptionData(ctx, cloneFrom, cloneTo)
if err == nil {
er = err
}
}
return l, er
} else {
// We have to encrypt/decrypt on the fly
destPath := cloneTo.ZapPath()
rsp, readErr := e.next.ReadNode(readCtx, &tree.ReadNodeRequest{
Node: cloneFrom,
})
if readErr != nil {
return 0, readErr
} else if rsp.Node == nil {
return 0, errors.NotFound("views.handler.encryption.CopyObject", "no node found that matches %s", cloneFrom)
}
cloneFrom = rsp.Node
reader, err := e.GetObject(readCtx, cloneFrom, &GetRequestData{StartOffset: 0, Length: cloneFrom.Size})
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.CopyObject: Different Clients - Read Source Error", zap.Any("srcInfo", srcInfo), cloneFrom.Zap("readFrom"), zap.Error(err))
return 0, err
}
defer reader.Close()
log.Logger(ctx).Debug("views.handler.encryption.CopyObject: from one DS to another - force UUID", cloneTo.Zap("to"), zap.Any("srcInfo", srcInfo), zap.Any("destInfo", destInfo))
if !move {
cloneTo.Uuid = uuid.New()
} else {
cloneTo.Uuid = cloneFrom.Uuid
}
putReqData := &PutRequestData{
Size: cloneFrom.Size,
Metadata: requestData.Metadata,
}
putReqData.Metadata[common.X_AMZ_META_CLEAR_SIZE] = fmt.Sprintf("%d", cloneFrom.Size)
putReqData.Metadata[common.X_AMZ_META_NODE_UUID] = cloneTo.Uuid
oi, err := e.PutObject(writeCtx, cloneTo, reader, putReqData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.CopyObject: Different Clients",
zap.Error(err),
cloneFrom.Zap("from"),
cloneTo.Zap("to"),
zap.Any("srcInfo", srcInfo),
zap.Any("destInfo", destInfo),
zap.Any("targetPath", destPath))
} else {
log.Logger(ctx).Debug("views.handler.encryption.CopyObject: Different Clients", rsp.Node.Zap("from"), zap.Int64("written", oi))
}
return oi, err
}
}
func (e *EncryptionHandler) MultipartCreate(ctx context.Context, target *tree.Node, requestData *MultipartRequestData) (string, error) {
var err error
branchInfo, ok := GetBranchInfo(ctx, "in")
if !ok || branchInfo.EncryptionMode != object.EncryptionMode_MASTER {
if _, ok := requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE]; ok {
// Not necessary for non-encrypted data source
delete(requestData.Metadata, common.X_AMZ_META_CLEAR_SIZE)
}
return e.next.MultipartCreate(ctx, target, requestData)
}
if _, ok := requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE]; !ok {
log.Logger(ctx).Warn("views.handler.encryption.MultiPartCreate: Missing special header to store clear size when uploading on encrypted data source - Setting ClearSize as unknown")
requestData.Metadata[common.X_AMZ_META_CLEAR_SIZE] = common.X_AMZ_META_CLEAR_SIZE_UNKOWN
}
clone := target.Clone()
if len(clone.Uuid) == 0 {
rsp, readErr := e.next.ReadNode(ctx, &tree.ReadNodeRequest{
Node: target,
})
if readErr != nil {
return "", errors.NotFound("views.handler.encryption.MultiPartCreate", "failed to get node UUID: %s", readErr)
}
if len(rsp.Node.Uuid) == 0 {
return "", errors.NotFound("views.handler.encryption.MultiPartCreate", "failed to get node UUID")
}
clone.Uuid = rsp.Node.Uuid
}
dsName := clone.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
if dsName == "" {
_ = clone.SetMeta(common.META_NAMESPACE_DATASOURCE_NAME, branchInfo.Name)
}
keyProtectionTool, err := e.getKeyProtectionTool(ctx)
if err != nil {
return "", err
}
streamClient, err := e.getNodeKeyManagerClient().SetNodeInfo(ctx)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to get data.key stream client", zap.Error(err))
return "", err
}
streamer := &setBlockStream{
client: streamClient,
nodeUuid: clone.Uuid,
keySent: false,
ctx: ctx,
}
info, err := e.getNodeInfoForWrite(ctx, clone)
if err != nil {
if errors.Parse(err.Error()).Code != 404 {
return "", err
}
info, err = e.createNodeInfo(ctx, clone)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to create node info", zap.Error(err))
return "", err
}
encryptionKeyPlainBytes := info.NodeKey.KeyData
info.NodeKey.KeyData, err = keyProtectionTool.GetEncrypted(ctx, branchInfo.EncryptionKey, encryptionKeyPlainBytes)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to encrypt node key", zap.Error(err))
return "", err
}
err = streamer.SendKey(info.NodeKey)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to create nodeInfo", zap.Error(err))
return "", err
}
} else {
err = streamer.ClearBlocks(clone.Uuid)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to clear old blocks", zap.Error(err))
return "", err
}
}
if err := streamer.Close(); err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartCreate: failed to close setNodeInfo stream", zap.Error(err))
}
return e.next.MultipartCreate(ctx, target, requestData)
}
func (e *EncryptionHandler) MultipartPutObjectPart(ctx context.Context, target *tree.Node, uploadID string, partNumberMarker int, reader io.Reader, requestData *PutRequestData) (minio.ObjectPart, error) {
var err error
branchInfo, ok := GetBranchInfo(ctx, "in")
if !ok || branchInfo.EncryptionMode != object.EncryptionMode_MASTER {
return e.next.MultipartPutObjectPart(ctx, target, uploadID, partNumberMarker, reader, requestData)
}
clone := target.Clone()
if len(clone.Uuid) == 0 {
rsp, readErr := e.next.ReadNode(ctx, &tree.ReadNodeRequest{
Node: target,
})
if readErr != nil {
return minio.ObjectPart{}, errors.NotFound("views.handler.encryption.MultiPartPutObject", "failed to get node UUID: %s", readErr)
}
if len(rsp.Node.Uuid) == 0 {
return minio.ObjectPart{}, errors.NotFound("views.handler.encryption.MultiPartPutObject", "failed to get node UUID")
}
clone.Uuid = rsp.Node.Uuid
}
dsName := clone.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
if dsName == "" {
_ = clone.SetMeta(common.META_NAMESPACE_DATASOURCE_NAME, branchInfo.Name)
}
keyProtectionTool, err := e.getKeyProtectionTool(ctx)
if err != nil {
return minio.ObjectPart{}, err
}
streamClient, err := e.getNodeKeyManagerClient().SetNodeInfo(ctx)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartPutObject: failed to save node encryption info", zap.Error(err))
return minio.ObjectPart{}, err
}
nodeBlocksStreamer := &setBlockStream{
client: streamClient,
nodeUuid: clone.Uuid,
keySent: true,
partId: uint32(partNumberMarker),
ctx: ctx,
}
info, err := e.getNodeInfoForWrite(ctx, clone)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartPutObject: failed to get node info", zap.Error(err))
return minio.ObjectPart{}, err
}
var encryptionKeyPlainBytes []byte
encryptionKeyPlainBytes, err = keyProtectionTool.GetDecrypted(ctx, branchInfo.EncryptionKey, info.NodeKey.KeyData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartPutObject: failed to unseal key", zap.Error(err))
return minio.ObjectPart{}, err
}
encryptionMaterials := crypto.NewAESGCMMaterials(info, nodeBlocksStreamer)
if err := encryptionMaterials.SetupEncryptMode(encryptionKeyPlainBytes, reader); err != nil {
return minio.ObjectPart{}, err
}
requestData.Md5Sum = nil
requestData.Sha256Sum = nil
plainSize := requestData.Size
requestData.Size = encryptionMaterials.CalculateOutputSize(requestData.Size, info.NodeKey.OwnerId)
part, err := e.next.MultipartPutObjectPart(ctx, target, uploadID, partNumberMarker, encryptionMaterials, requestData)
if err != nil {
log.Logger(ctx).Error("views.handler.encryption.MultiPartPutObject: next handler failed", zap.Error(err))
}
// Replace part Size with plain size value
part.Size = plainSize
return part, err
}
func (e *EncryptionHandler) copyNodeEncryptionData(ctx context.Context, source *tree.Node, copy *tree.Node) error {
nodeEncryptionClient := e.nodeKeyManagerClient
if nodeEncryptionClient == nil {
nodeEncryptionClient = encryption.NewNodeKeyManagerClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ENC_KEY, defaults.NewClient())
}
_, err := nodeEncryptionClient.CopyNodeInfo(ctx, &encryption.CopyNodeInfoRequest{
NodeUuid: source.Uuid,
NodeCopyUuid: copy.Uuid,
})
return err
}
func (e *EncryptionHandler) getNodeInfoForRead(ctx context.Context, node *tree.Node, requestData *GetRequestData) (*encryption.NodeInfo, int64, int64, int64, error) {
nodeEncryptionClient := e.nodeKeyManagerClient
if nodeEncryptionClient == nil {
nodeEncryptionClient = encryption.NewNodeKeyManagerClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ENC_KEY, defaults.NewClient())
}
fullRead := requestData.StartOffset == 0 && (requestData.Length <= 0 || requestData.Length == node.Size)
dsName := node.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
rsp, err := nodeEncryptionClient.GetNodeInfo(ctx, &encryption.GetNodeInfoRequest{
UserId: fmt.Sprintf("ds:%s", dsName),
NodeId: node.Uuid,
WithRange: !fullRead,
PlainOffset: requestData.StartOffset,
PlainLength: requestData.Length,
})
if err != nil {
return nil, 0, 0, 0, err
}
return rsp.NodeInfo, int64(rsp.EncryptedOffset), int64(rsp.EncryptedCount), rsp.HeadSKippedPlainBytesCount, nil
}
func (e *EncryptionHandler) getNodeInfoForWrite(ctx context.Context, node *tree.Node) (*encryption.NodeInfo, error) {
nodeEncryptionClient := e.nodeKeyManagerClient
if nodeEncryptionClient == nil {
nodeEncryptionClient = encryption.NewNodeKeyManagerClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ENC_KEY, defaults.NewClient())
}
dsName := node.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
rsp, err := nodeEncryptionClient.GetNodeInfo(ctx, &encryption.GetNodeInfoRequest{
UserId: fmt.Sprintf("ds:%s", dsName),
NodeId: node.Uuid,
WithRange: false,
})
if err != nil {
return nil, err
}
return rsp.NodeInfo, nil
}
func (e *EncryptionHandler) getNodeInfo(ctx context.Context, request *encryption.GetNodeInfoRequest) (*encryption.GetNodeInfoResponse, error) {
nodeEncryptionClient := e.nodeKeyManagerClient
if nodeEncryptionClient == nil {
nodeEncryptionClient = encryption.NewNodeKeyManagerClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ENC_KEY, defaults.NewClient())
}
return nodeEncryptionClient.GetNodeInfo(ctx, request)
}
func (e *EncryptionHandler) createNodeInfo(ctx context.Context, node *tree.Node) (*encryption.NodeInfo, error) {
dsName := node.GetStringMeta(common.META_NAMESPACE_DATASOURCE_NAME)
user := fmt.Sprintf("ds:%s", dsName)
info := new(encryption.NodeInfo)
//we generate a new key
info.NodeKey = &encryption.NodeKey{
UserId: user,
NodeId: node.Uuid,
OwnerId: user,
}
encKey, err := crypto.RandomBytes(32)
if err != nil {
return info, err
}
info.NodeKey.KeyData = encKey
info.Node = new(encryption.Node)
info.Node.Legacy = false
info.Node.NodeId = node.Uuid
return info, nil
}
func (e *EncryptionHandler) getKeyProtectionTool(ctx context.Context) (key.UserKeyTool, error) {
tool := e.userKeyTool
var err error
if tool == nil {
tool, err = key.MasterKeyTool(ctx)
if err != nil {
return nil, err
}
}
return tool, err
}
func (e *EncryptionHandler) getNodeKeyManagerClient() encryption.NodeKeyManagerClient {
nodeEncryptionClient := e.nodeKeyManagerClient
if nodeEncryptionClient == nil {
nodeEncryptionClient = encryption.NewNodeKeyManagerClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ENC_KEY, defaults.NewClient())
}
return nodeEncryptionClient
}
// setBlockStream
type setBlockStream struct {
client encryption.NodeKeyManager_SetNodeInfoClient
keySent bool
nodeUuid string
position uint32
partId uint32
ctx context.Context
err error
}
func (streamer *setBlockStream) SendKey(key *encryption.NodeKey) error {
if streamer.err != nil {
return streamer.err
}
key.NodeId = streamer.nodeUuid
streamer.err = streamer.client.SendMsg(&encryption.SetNodeInfoRequest{
Action: "key",
SetNodeKey: &encryption.SetNodeKeyRequest{
NodeKey: key,
},
})
if streamer.err != nil {
return streamer.err
}
var rsp encryption.SetNodeInfoResponse
streamer.err = streamer.client.RecvMsg(&rsp)
if streamer.err != nil {
return streamer.err
} else if rsp.ErrorText != "" {
return errors.Parse(rsp.ErrorText)
}
return streamer.err
}
func (streamer *setBlockStream) SendBlock(block *encryption.Block) error {
if streamer.err != nil {
return streamer.err
}
streamer.position++
block.Position = streamer.position
block.PartId = streamer.partId
block.Nonce = nil
setNodeInfoRequest := &encryption.SetNodeInfoRequest{
Action: "block",
SetBlock: &encryption.SetNodeBlockRequest{
NodeUuid: streamer.nodeUuid,
Block: block,
},
}
streamer.err = streamer.client.SendMsg(setNodeInfoRequest)
if streamer.err != nil {
return streamer.err
}
var rsp encryption.SetNodeInfoResponse
streamer.err = streamer.client.RecvMsg(&rsp)
if streamer.err != nil {
return streamer.err
} else if rsp.ErrorText != "" {
return errors.Parse(rsp.ErrorText)
}
return nil
}
func (streamer *setBlockStream) ClearBlocks(NodeId string) error {
if streamer.err != nil {
return streamer.err
}
setNodeInfoRequest := &encryption.SetNodeInfoRequest{
Action: "clearBlocks",
SetBlock: &encryption.SetNodeBlockRequest{
NodeUuid: streamer.nodeUuid,
},
}
streamer.err = streamer.client.SendMsg(setNodeInfoRequest)
if streamer.err != nil {
return streamer.err
}
var rsp encryption.SetNodeInfoResponse
streamer.err = streamer.client.RecvMsg(&rsp)
if streamer.err != nil {
return streamer.err
} else if rsp.ErrorText != "" {
return errors.Parse(rsp.ErrorText)
}
return nil
}
func (streamer *setBlockStream) Close() error {
// send empty node to notify the end of the exchange
err := streamer.client.Send(&encryption.SetNodeInfoRequest{
Action: "close",
})
if err != nil {
log.Logger(streamer.ctx).Warn("data.key.service.SetBlockStream: could not send close action")
}
var rsp encryption.SetNodeInfoResponse
err = streamer.client.RecvMsg(&rsp)
if err != nil {
log.Logger(streamer.ctx).Warn("data.key.service.SetBlockStream: could not receive close action response")
}
return streamer.client.Close()
}