-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtdf.go
1045 lines (872 loc) · 31 KB
/
tdf.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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sdk
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"strings"
"github.com/google/uuid"
"github.com/opentdf/platform/lib/ocrypto"
"github.com/opentdf/platform/sdk/auth"
"github.com/opentdf/platform/sdk/internal/archive"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
const (
sdkVersion = "4.3.0"
maxFileSizeSupported = 68719476736 // 64gb
defaultMimeType = "application/octet-stream"
tdfAsZip = "zip"
gcmIvSize = 12
aesBlockSize = 16
hmacIntegrityAlgorithm = "HS256"
gmacIntegrityAlgorithm = "GMAC"
tdfZipReference = "reference"
kKeySize = 32
kWrapped = "wrapped"
kKasProtocol = "kas"
kSplitKeyType = "split"
kGCMCipherAlgorithm = "AES-256-GCM"
kGMACPayloadLength = 16
kAssertionSignature = "assertionSig"
kAssertionHash = "assertionHash"
kClientPublicKey = "clientPublicKey"
kSignedRequestToken = "signedRequestToken"
kKasURL = "url"
kRewrapV2 = "/v2/rewrap"
kAuthorizationKey = "Authorization"
kContentTypeKey = "Content-Type"
kAcceptKey = "Accept"
kContentTypeJSONValue = "application/json"
kEntityWrappedKey = "entityWrappedKey"
kPolicy = "policy"
kHmacIntegrityAlgorithm = "HS256"
kGmacIntegrityAlgorithm = "GMAC"
)
// Loads and reads ZTDF files
type Reader struct {
tokenSource auth.AccessTokenSource
dialOptions []grpc.DialOption
manifest Manifest
unencryptedMetadata []byte
tdfReader archive.TDFReader
cursor int64
aesGcm ocrypto.AesGcm
payloadSize int64
payloadKey []byte
kasSessionKey ocrypto.RsaKeyPair
config TDFReaderConfig
}
type TDFObject struct {
manifest Manifest
size int64
aesGcm ocrypto.AesGcm
payloadKey [kKeySize]byte
}
func (t TDFObject) Size() int64 {
return t.size
}
// CreateTDF reads plain text from the given reader and saves it to the writer, subject to the given options
func (s SDK) CreateTDF(writer io.Writer, reader io.ReadSeeker, opts ...TDFOption) (*TDFObject, error) {
return s.CreateTDFContext(context.Background(), writer, reader, opts...)
}
func (s SDK) defaultKases(c *TDFConfig) []string {
allk := make([]string, 0, len(c.kasInfoList))
defk := make([]string, 0)
for _, k := range c.kasInfoList {
if k.Default {
defk = append(defk, k.URL)
} else if len(defk) == 0 {
allk = append(allk, k.URL)
}
}
if len(defk) == 0 {
return allk
}
return defk
}
// CreateTDFContext reads plain text from the given reader and saves it to the writer, subject to the given options
func (s SDK) CreateTDFContext(ctx context.Context, writer io.Writer, reader io.ReadSeeker, opts ...TDFOption) (*TDFObject, error) { //nolint:funlen, gocognit, lll // Better readability keeping it as is
inputSize, err := reader.Seek(0, io.SeekEnd)
if err != nil {
return nil, fmt.Errorf("readSeeker.Seek failed: %w", err)
}
if inputSize > maxFileSizeSupported {
return nil, errFileTooLarge
}
_, err = reader.Seek(0, io.SeekStart)
if err != nil {
return nil, fmt.Errorf("readSeeker.Seek failed: %w", err)
}
tdfConfig, err := newTDFConfig(opts...)
if err != nil {
return nil, fmt.Errorf("NewTDFConfig failed: %w", err)
}
if tdfConfig.autoconfigure {
var g granter
if len(tdfConfig.attributeValues) > 0 {
g, err = newGranterFromAttributes(s.kasKeyCache, tdfConfig.attributeValues...)
} else if len(tdfConfig.attributes) > 0 {
g, err = newGranterFromService(ctx, s.kasKeyCache, s.Attributes, tdfConfig.attributes...)
}
if err != nil {
return nil, err
}
dk := s.defaultKases(tdfConfig)
tdfConfig.splitPlan, err = g.plan(dk, func() string {
return uuid.New().String()
})
if err != nil {
return nil, err
}
}
tdfObject := &TDFObject{}
err = s.prepareManifest(ctx, tdfObject, *tdfConfig)
if err != nil {
return nil, fmt.Errorf("fail to create a new split key: %w", err)
}
segmentSize := tdfConfig.defaultSegmentSize
if segmentSize > maxSegmentSize {
return nil, fmt.Errorf("segment size too large: %d", segmentSize)
} else if segmentSize < minSegmentSize {
return nil, fmt.Errorf("segment size too small: %d", segmentSize)
}
totalSegments := inputSize / segmentSize
if inputSize%segmentSize != 0 {
totalSegments++
}
// empty payload we still want to create a payload
if totalSegments == 0 {
totalSegments = 1
}
encryptedSegmentSize := segmentSize + gcmIvSize + aesBlockSize
payloadSize := inputSize + (totalSegments * (gcmIvSize + aesBlockSize))
tdfWriter := archive.NewTDFWriter(writer)
err = tdfWriter.SetPayloadSize(payloadSize)
if err != nil {
return nil, fmt.Errorf("archive.SetPayloadSize failed: %w", err)
}
var readPos int64
var aggregateHash string
readBuf := bytes.NewBuffer(make([]byte, 0, tdfConfig.defaultSegmentSize))
for totalSegments != 0 { // adjust read size
readSize := segmentSize
if (inputSize - readPos) < segmentSize {
readSize = inputSize - readPos
}
n, err := reader.Read(readBuf.Bytes()[:readSize])
if err != nil {
return nil, fmt.Errorf("io.ReadSeeker.Read failed: %w", err)
}
if int64(n) != readSize {
return nil, fmt.Errorf("io.ReadSeeker.Read size mismatch")
}
cipherData, err := tdfObject.aesGcm.Encrypt(readBuf.Bytes()[:readSize])
if err != nil {
return nil, fmt.Errorf("io.ReadSeeker.Read failed: %w", err)
}
err = tdfWriter.AppendPayload(cipherData)
if err != nil {
return nil, fmt.Errorf("io.writer.Write failed: %w", err)
}
segmentSig, err := calculateSignature(cipherData, tdfObject.payloadKey[:],
tdfConfig.segmentIntegrityAlgorithm, false)
if err != nil {
return nil, fmt.Errorf("splitKey.GetSignaturefailed: %w", err)
}
aggregateHash += segmentSig
segmentInfo := Segment{
Hash: string(ocrypto.Base64Encode([]byte(segmentSig))),
Size: readSize,
EncryptedSize: int64(len(cipherData)),
}
tdfObject.manifest.EncryptionInformation.IntegrityInformation.Segments =
append(tdfObject.manifest.EncryptionInformation.IntegrityInformation.Segments, segmentInfo)
totalSegments--
readPos += readSize
}
rootSignature, err := calculateSignature([]byte(aggregateHash), tdfObject.payloadKey[:],
tdfConfig.integrityAlgorithm, false)
if err != nil {
return nil, fmt.Errorf("splitKey.GetSignaturefailed: %w", err)
}
sig := string(ocrypto.Base64Encode([]byte(rootSignature)))
tdfObject.manifest.EncryptionInformation.IntegrityInformation.RootSignature.Signature = sig
integrityAlgStr := gmacIntegrityAlgorithm
if tdfConfig.integrityAlgorithm == HS256 {
integrityAlgStr = hmacIntegrityAlgorithm
}
tdfObject.manifest.EncryptionInformation.IntegrityInformation.RootSignature.Algorithm = integrityAlgStr
tdfObject.manifest.EncryptionInformation.IntegrityInformation.DefaultSegmentSize = segmentSize
tdfObject.manifest.EncryptionInformation.IntegrityInformation.DefaultEncryptedSegSize = encryptedSegmentSize
segIntegrityAlgStr := gmacIntegrityAlgorithm
if tdfConfig.segmentIntegrityAlgorithm == HS256 {
segIntegrityAlgStr = hmacIntegrityAlgorithm
}
tdfObject.manifest.EncryptionInformation.IntegrityInformation.SegmentHashAlgorithm = segIntegrityAlgStr
tdfObject.manifest.EncryptionInformation.Method.IsStreamable = true
// add payload info
mimeType := tdfConfig.mimeType
if mimeType == "" {
mimeType = defaultMimeType
}
tdfObject.manifest.Payload.MimeType = mimeType
tdfObject.manifest.Payload.Protocol = tdfAsZip
tdfObject.manifest.Payload.Type = tdfZipReference
tdfObject.manifest.Payload.URL = archive.TDFPayloadFileName
tdfObject.manifest.Payload.IsEncrypted = true
var signedAssertion []Assertion
for _, assertion := range tdfConfig.assertions {
// Store a temporary assertion
tmpAssertion := Assertion{}
tmpAssertion.ID = assertion.ID
tmpAssertion.Type = assertion.Type
tmpAssertion.Scope = assertion.Scope
tmpAssertion.Statement = assertion.Statement
tmpAssertion.AppliesToState = assertion.AppliesToState
hashOfAssertionAsHex, err := tmpAssertion.GetHash()
if err != nil {
return nil, err
}
hashOfAssertion := make([]byte, hex.DecodedLen(len(hashOfAssertionAsHex)))
_, err = hex.Decode(hashOfAssertion, hashOfAssertionAsHex)
if err != nil {
return nil, fmt.Errorf("error decoding hex string: %w", err)
}
var completeHashBuilder strings.Builder
completeHashBuilder.WriteString(aggregateHash)
completeHashBuilder.Write(hashOfAssertion)
encoded := ocrypto.Base64Encode([]byte(completeHashBuilder.String()))
var assertionSigningKey = AssertionKey{}
// Set default to HS256 and payload key
assertionSigningKey.Alg = AssertionKeyAlgHS256
assertionSigningKey.Key = tdfObject.payloadKey[:]
if !assertion.SigningKey.IsEmpty() {
assertionSigningKey = assertion.SigningKey
}
if err := tmpAssertion.Sign(string(hashOfAssertionAsHex), string(encoded), assertionSigningKey); err != nil {
return nil, fmt.Errorf("failed to sign assertion: %w", err)
}
signedAssertion = append(signedAssertion, tmpAssertion)
}
tdfObject.manifest.Assertions = signedAssertion
manifestAsStr, err := json.Marshal(tdfObject.manifest)
if err != nil {
return nil, fmt.Errorf("json.Marshal failed:%w", err)
}
err = tdfWriter.AppendManifest(string(manifestAsStr))
if err != nil {
return nil, fmt.Errorf("TDFWriter.AppendManifest failed:%w", err)
}
tdfObject.size, err = tdfWriter.Finish()
if err != nil {
return nil, fmt.Errorf("TDFWriter.Finish failed:%w", err)
}
return tdfObject, nil
}
func (t *TDFObject) Manifest() Manifest {
return t.manifest
}
func (r *Reader) Manifest() Manifest {
return r.manifest
}
// prepare the manifest for TDF
func (s SDK) prepareManifest(ctx context.Context, t *TDFObject, tdfConfig TDFConfig) error { //nolint:funlen,gocognit // Better readability keeping it as is
manifest := Manifest{}
version, err := ParseVersion(sdkVersion)
if err != nil {
return fmt.Errorf("ReadVersion failed:%w", err)
}
manifest.TDFVersion = version.String()
if len(tdfConfig.splitPlan) == 0 && len(tdfConfig.kasInfoList) == 0 {
return fmt.Errorf("%w: no key access template specified or inferred", errInvalidKasInfo)
}
manifest.EncryptionInformation.KeyAccessType = kSplitKeyType
policyObj, err := createPolicyObject(tdfConfig.attributes)
if err != nil {
return fmt.Errorf("fail to create policy object:%w", err)
}
policyObjectAsStr, err := json.Marshal(policyObj)
if err != nil {
return fmt.Errorf("json.Marshal failed:%w", err)
}
base64PolicyObject := ocrypto.Base64Encode(policyObjectAsStr)
symKeys := make([][]byte, 0)
latestKASInfo := make(map[string]KASInfo)
if len(tdfConfig.splitPlan) == 0 {
// Default split plan: Split keys across all kases
tdfConfig.splitPlan = make([]keySplitStep, len(tdfConfig.kasInfoList))
for i, kasInfo := range tdfConfig.kasInfoList {
tdfConfig.splitPlan[i].KAS = kasInfo.URL
if len(tdfConfig.kasInfoList) > 1 {
tdfConfig.splitPlan[i].SplitID = fmt.Sprintf("s-%d", i)
}
if kasInfo.PublicKey != "" {
latestKASInfo[kasInfo.URL] = kasInfo
}
}
}
// Seed anything passed in manually
for _, kasInfo := range tdfConfig.kasInfoList {
if kasInfo.PublicKey != "" {
latestKASInfo[kasInfo.URL] = kasInfo
}
}
// split plan: restructure by conjunctions
conjunction := make(map[string][]KASInfo)
var splitIDs []string
for _, splitInfo := range tdfConfig.splitPlan {
// Public key was passed in with kasInfoList
// TODO first look up in attribute information / add to split plan?
ki, ok := latestKASInfo[splitInfo.KAS]
if !ok || ki.PublicKey == "" {
k, err := s.getPublicKey(ctx, splitInfo.KAS, "rsa:2048")
if err != nil {
return fmt.Errorf("unable to retrieve public key from KAS at [%s]: %w", splitInfo.KAS, err)
}
latestKASInfo[splitInfo.KAS] = *k
ki = *k
}
if _, ok = conjunction[splitInfo.SplitID]; ok {
conjunction[splitInfo.SplitID] = append(conjunction[splitInfo.SplitID], ki)
} else {
conjunction[splitInfo.SplitID] = []KASInfo{ki}
splitIDs = append(splitIDs, splitInfo.SplitID)
}
}
for _, splitID := range splitIDs {
symKey, err := ocrypto.RandomBytes(kKeySize)
if err != nil {
return fmt.Errorf("ocrypto.RandomBytes failed:%w", err)
}
symKeys = append(symKeys, symKey)
// policy binding
policyBindingHash := hex.EncodeToString(ocrypto.CalculateSHA256Hmac(symKey, base64PolicyObject))
pbstring := string(ocrypto.Base64Encode([]byte(policyBindingHash)))
policyBinding := PolicyBinding{
Alg: "HS256",
Hash: pbstring,
}
// encrypted metadata
// add meta data
var encryptedMetadata string
if len(tdfConfig.metaData) > 0 {
gcm, err := ocrypto.NewAESGcm(symKey)
if err != nil {
return fmt.Errorf("ocrypto.NewAESGcm failed:%w", err)
}
emb, err := gcm.Encrypt([]byte(tdfConfig.metaData))
if err != nil {
return fmt.Errorf("ocrypto.AesGcm.encrypt failed:%w", err)
}
iv := emb[:ocrypto.GcmStandardNonceSize]
metadata := EncryptedMetadata{
Cipher: string(ocrypto.Base64Encode(emb)),
Iv: string(ocrypto.Base64Encode(iv)),
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf(" json.Marshal failed:%w", err)
}
encryptedMetadata = string(ocrypto.Base64Encode(metadataJSON))
}
for _, kasInfo := range conjunction[splitID] {
if len(kasInfo.PublicKey) == 0 {
return fmt.Errorf("splitID:[%s], kas:[%s]: %w", splitID, kasInfo.URL, errKasPubKeyMissing)
}
// wrap the key with kas public key
asymEncrypt, err := ocrypto.NewAsymEncryption(kasInfo.PublicKey)
if err != nil {
return fmt.Errorf("ocrypto.NewAsymEncryption failed:%w", err)
}
wrappedKey, err := asymEncrypt.Encrypt(symKey)
if err != nil {
return fmt.Errorf("ocrypto.AsymEncryption.encrypt failed:%w", err)
}
keyAccess := KeyAccess{
KeyType: kWrapped,
KasURL: kasInfo.URL,
KID: kasInfo.KID,
Protocol: kKasProtocol,
PolicyBinding: policyBinding,
EncryptedMetadata: encryptedMetadata,
SplitID: splitID,
WrappedKey: string(ocrypto.Base64Encode(wrappedKey)),
}
manifest.EncryptionInformation.KeyAccessObjs = append(manifest.EncryptionInformation.KeyAccessObjs, keyAccess)
}
}
manifest.EncryptionInformation.Policy = string(base64PolicyObject)
manifest.EncryptionInformation.Method.Algorithm = kGCMCipherAlgorithm
// create the payload key by XOR all the keys in key access object.
for _, symKey := range symKeys {
for keyByteIndex, keyByte := range symKey {
t.payloadKey[keyByteIndex] ^= keyByte
}
}
gcm, err := ocrypto.NewAESGcm(t.payloadKey[:])
if err != nil {
return fmt.Errorf(" ocrypto.NewAESGcm failed:%w", err)
}
t.manifest = manifest
t.aesGcm = gcm
return nil
}
// create policy object
func createPolicyObject(attributes []AttributeValueFQN) (PolicyObject, error) {
uuidObj, err := uuid.NewUUID()
if err != nil {
return PolicyObject{}, fmt.Errorf("uuid.NewUUID failed: %w", err)
}
policyObj := PolicyObject{}
policyObj.UUID = uuidObj.String()
for _, attribute := range attributes {
attributeObj := attributeObject{}
attributeObj.Attribute = attribute.String()
policyObj.Body.DataAttributes = append(policyObj.Body.DataAttributes, attributeObj)
policyObj.Body.Dissem = make([]string, 0)
}
return policyObj, nil
}
// LoadTDF loads the tdf and prepare for reading the payload from TDF
func (s SDK) LoadTDF(reader io.ReadSeeker, opts ...TDFReaderOption) (*Reader, error) {
// create tdf reader
tdfReader, err := archive.NewTDFReader(reader)
if err != nil {
return nil, fmt.Errorf("archive.NewTDFReader failed: %w", err)
}
config, err := newTDFReaderConfig(opts...)
if err != nil {
return nil, fmt.Errorf("newAssertionConfig failed: %w", err)
}
manifest, err := tdfReader.Manifest()
if err != nil {
return nil, fmt.Errorf("tdfReader.Manifest failed: %w", err)
}
manifestObj := &Manifest{}
err = json.Unmarshal([]byte(manifest), manifestObj)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal failed:%w", err)
}
return &Reader{
tokenSource: s.tokenSource,
dialOptions: s.dialOptions,
tdfReader: tdfReader,
manifest: *manifestObj,
kasSessionKey: *s.config.kasSessionKey,
config: *config,
}, nil
}
// Do any network based operations required.
// This allows making the requests cancellable
func (r *Reader) Init(ctx context.Context) error {
if r.payloadKey != nil {
return nil
}
return r.doPayloadKeyUnwrap(ctx)
}
// Read reads up to len(p) bytes into p. It returns the number of bytes
// read (0 <= n <= len(p)) and any error encountered. It returns an
// io.EOF error when the stream ends.
func (r *Reader) Read(p []byte) (int, error) {
if r.payloadKey == nil {
err := r.doPayloadKeyUnwrap(context.Background())
if err != nil {
return 0, fmt.Errorf("reader.Read failed: %w", err)
}
}
n, err := r.ReadAt(p, r.cursor)
r.cursor += int64(n)
return n, err
}
// WriteTo writes data to writer until there's no more data to write or
// when an error occurs. This implements the io.WriterTo interface.
func (r *Reader) WriteTo(writer io.Writer) (int64, error) {
if r.payloadKey == nil {
err := r.doPayloadKeyUnwrap(context.Background())
if err != nil {
return 0, fmt.Errorf("reader.WriteTo failed: %w", err)
}
}
isLegacyTDF := r.manifest.TDFVersion == ""
var totalBytes int64
var payloadReadOffset int64
for _, seg := range r.manifest.EncryptionInformation.IntegrityInformation.Segments {
readBuf, err := r.tdfReader.ReadPayload(payloadReadOffset, seg.EncryptedSize)
if err != nil {
return totalBytes, fmt.Errorf("TDFReader.ReadPayload failed: %w", err)
}
if int64(len(readBuf)) != seg.EncryptedSize {
return totalBytes, ErrSegSizeMismatch
}
segHashAlg := r.manifest.EncryptionInformation.IntegrityInformation.SegmentHashAlgorithm
sigAlg := HS256
if strings.EqualFold(gmacIntegrityAlgorithm, segHashAlg) {
sigAlg = GMAC
}
payloadSig, err := calculateSignature(readBuf, r.payloadKey, sigAlg, isLegacyTDF)
if err != nil {
return totalBytes, fmt.Errorf("splitKey.GetSignaturefailed: %w", err)
}
if seg.Hash != string(ocrypto.Base64Encode([]byte(payloadSig))) {
return totalBytes, ErrSegSigValidation
}
writeBuf, err := r.aesGcm.Decrypt(readBuf)
if err != nil {
return totalBytes, fmt.Errorf("splitKey.decrypt failed: %w", err)
}
n, err := writer.Write(writeBuf)
if err != nil {
return totalBytes, fmt.Errorf("io.writer.write failed: %w", err)
}
if n != len(writeBuf) {
return totalBytes, errWriteFailed
}
payloadReadOffset += seg.EncryptedSize
totalBytes += int64(n)
}
return totalBytes, nil
}
// ReadAt reads len(p) bytes into p starting at offset off
// in the underlying input source. It returns the number
// of bytes read (0 <= n <= len(p)) and any error encountered. It returns an
// io.EOF error when the stream ends.
// NOTE: For larger tdf sizes use sdk.GetTDFPayload for better performance
func (r *Reader) ReadAt(buf []byte, offset int64) (int, error) { //nolint:funlen, gocognit // Better readability keeping it as is for now
if r.payloadKey == nil {
err := r.doPayloadKeyUnwrap(context.Background())
if err != nil {
return 0, fmt.Errorf("reader.ReadAt failed: %w", err)
}
}
if offset < 0 {
return 0, ErrTDFPayloadInvalidOffset
}
defaultSegmentSize := r.manifest.EncryptionInformation.IntegrityInformation.DefaultSegmentSize
var start = math.Floor(float64(offset) / float64(defaultSegmentSize))
var end = math.Ceil(float64(offset+int64(len(buf))) / float64(defaultSegmentSize))
firstSegment := int64(start)
lastSegment := int64(end)
if firstSegment > lastSegment {
return 0, ErrTDFPayloadReadFail
}
if offset > r.payloadSize {
return 0, ErrTDFPayloadReadFail
}
isLegacyTDF := r.manifest.TDFVersion == ""
var decryptedBuf bytes.Buffer
var payloadReadOffset int64
for index, seg := range r.manifest.EncryptionInformation.IntegrityInformation.Segments {
if firstSegment > int64(index) {
payloadReadOffset += seg.EncryptedSize
continue
}
readBuf, err := r.tdfReader.ReadPayload(payloadReadOffset, seg.EncryptedSize)
if err != nil {
return 0, fmt.Errorf("TDFReader.ReadPayload failed: %w", err)
}
if int64(len(readBuf)) != seg.EncryptedSize {
return 0, ErrSegSizeMismatch
}
segHashAlg := r.manifest.EncryptionInformation.IntegrityInformation.SegmentHashAlgorithm
sigAlg := HS256
if strings.EqualFold(gmacIntegrityAlgorithm, segHashAlg) {
sigAlg = GMAC
}
payloadSig, err := calculateSignature(readBuf, r.payloadKey, sigAlg, isLegacyTDF)
if err != nil {
return 0, fmt.Errorf("splitKey.GetSignaturefailed: %w", err)
}
if seg.Hash != string(ocrypto.Base64Encode([]byte(payloadSig))) {
return 0, ErrSegSigValidation
}
writeBuf, err := r.aesGcm.Decrypt(readBuf)
if err != nil {
return 0, fmt.Errorf("splitKey.decrypt failed: %w", err)
}
n, err := decryptedBuf.Write(writeBuf)
if err != nil {
return 0, fmt.Errorf("bytes.Buffer.writer.write failed: %w", err)
}
if n != len(writeBuf) {
return 0, errWriteFailed
}
payloadReadOffset += seg.EncryptedSize
// finish segments to decrypt
if int64(index) == lastSegment {
break
}
}
var err error
bufLen := int64(len(buf))
if (offset + int64(len(buf))) > r.payloadSize {
bufLen = r.payloadSize - offset
err = io.EOF
}
startIndex := offset - (firstSegment * defaultSegmentSize)
copy(buf[:bufLen], decryptedBuf.Bytes()[startIndex:startIndex+bufLen])
return int(bufLen), err
}
// UnencryptedMetadata return decrypted metadata in manifest.
func (r *Reader) UnencryptedMetadata() ([]byte, error) {
if r.payloadKey == nil {
err := r.doPayloadKeyUnwrap(context.Background())
if err != nil {
return nil, fmt.Errorf("reader.UnencryptedMetadata failed: %w", err)
}
}
return r.unencryptedMetadata, nil
}
// Policy returns a copy of the policy object in manifest, if it is valid.
// Otherwise, returns an error.
func (r *Reader) Policy() (PolicyObject, error) {
policyObj := PolicyObject{}
policy, err := ocrypto.Base64Decode([]byte(r.manifest.Policy))
if err != nil {
return policyObj, fmt.Errorf("ocrypto.Base64Decode failed:%w", err)
}
err = json.Unmarshal(policy, &policyObj)
if err != nil {
return policyObj, fmt.Errorf("json.Unmarshal failed: %w", err)
}
return policyObj, nil
}
// DataAttributes return the data attributes present in tdf.
func (r *Reader) DataAttributes() ([]string, error) {
policy, err := ocrypto.Base64Decode([]byte(r.manifest.Policy))
if err != nil {
return nil, fmt.Errorf("ocrypto.Base64Decode failed:%w", err)
}
policyObj := PolicyObject{}
err = json.Unmarshal(policy, &policyObj)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal failed: %w", err)
}
attributes := make([]string, 0)
attributeObjs := policyObj.Body.DataAttributes
for _, attributeObj := range attributeObjs {
attributes = append(attributes, attributeObj.Attribute)
}
return attributes, nil
}
/*
*WARNING:* Using this function is unsafe since KAS will no longer be able to prevent access to the key.
Retrieve the payload key, either from performing an unwrap or from a previous unwrap,
and write it to a user buffer.
OUTPUTS:
- []byte - Byte array containing the DEK.
- error - If an error occurred while processing
*/
func (r *Reader) UnsafePayloadKeyRetrieval() ([]byte, error) {
if r.payloadKey == nil {
err := r.doPayloadKeyUnwrap(context.Background())
if err != nil {
return nil, fmt.Errorf("reader.PayloadKey failed: %w", err)
}
}
return r.payloadKey, nil
}
// Unwraps the payload key, if possible, using the access service
func (r *Reader) doPayloadKeyUnwrap(ctx context.Context) error { //nolint:gocognit // Better readability keeping it as is
var unencryptedMetadata []byte
var payloadKey [kKeySize]byte
knownSplits := make(map[string]bool)
foundSplits := make(map[string]bool)
skippedSplits := make(map[keySplitStep]error)
mixedSplits := len(r.manifest.KeyAccessObjs) > 1 && r.manifest.KeyAccessObjs[0].SplitID != ""
for _, keyAccessObj := range r.manifest.EncryptionInformation.KeyAccessObjs {
client := newKASClient(r.dialOptions, r.tokenSource, &r.kasSessionKey)
ss := keySplitStep{KAS: keyAccessObj.KasURL, SplitID: keyAccessObj.SplitID}
var err error
var wrappedKey []byte
if !mixedSplits { //nolint:nestif // todo: subfunction
wrappedKey, err = client.unwrap(ctx, keyAccessObj, r.manifest.EncryptionInformation.Policy)
if err != nil {
errToReturn := fmt.Errorf("doPayloadKeyUnwrap splitKey.rewrap failed: %w", err)
if strings.Contains(err.Error(), codes.InvalidArgument.String()) {
return fmt.Errorf("%w: %w", ErrRewrapBadRequest, errToReturn)
}
if strings.Contains(err.Error(), codes.PermissionDenied.String()) {
return fmt.Errorf("%w: %w", errRewrapForbidden, errToReturn)
}
return errToReturn
}
} else {
knownSplits[ss.SplitID] = true
if foundSplits[ss.SplitID] {
// already found
continue
}
wrappedKey, err = client.unwrap(ctx, keyAccessObj, r.manifest.EncryptionInformation.Policy)
if err != nil {
errToReturn := fmt.Errorf("kao unwrap failed for split %v: %w", ss, err)
if !strings.Contains(err.Error(), codes.InvalidArgument.String()) {
skippedSplits[ss] = fmt.Errorf("%w: %w", ErrRewrapBadRequest, errToReturn)
}
if !strings.Contains(err.Error(), codes.PermissionDenied.String()) {
skippedSplits[ss] = fmt.Errorf("%w: %w", errRewrapForbidden, errToReturn)
}
skippedSplits[ss] = errToReturn
continue
}
}
for keyByteIndex, keyByte := range wrappedKey {
payloadKey[keyByteIndex] ^= keyByte
}
foundSplits[ss.SplitID] = true
if len(keyAccessObj.EncryptedMetadata) != 0 {
gcm, err := ocrypto.NewAESGcm(wrappedKey)
if err != nil {
return fmt.Errorf("ocrypto.NewAESGcm failed:%w", err)
}
decodedMetaData, err := ocrypto.Base64Decode([]byte(keyAccessObj.EncryptedMetadata))
if err != nil {
return fmt.Errorf("ocrypto.Base64Decode failed:%w", err)
}
metadata := EncryptedMetadata{}
err = json.Unmarshal(decodedMetaData, &metadata)
if err != nil {
return fmt.Errorf("json.Unmarshal failed:%w", err)
}
encodedCipherText := metadata.Cipher
cipherText, _ := ocrypto.Base64Decode([]byte(encodedCipherText))
metaData, err := gcm.Decrypt(cipherText)
if err != nil {
return fmt.Errorf("ocrypto.AesGcm.encrypt failed:%w", err)
}
unencryptedMetadata = metaData
}
}
if mixedSplits && len(knownSplits) > len(foundSplits) {
v := make([]error, 1, len(skippedSplits))
v[0] = fmt.Errorf("splitKey.unable to reconstruct split key: %v", skippedSplits)
for _, e := range skippedSplits {
v = append(v, e)
}
return errors.Join(v...)
}
aggregateHash := &bytes.Buffer{}
for _, segment := range r.manifest.EncryptionInformation.IntegrityInformation.Segments {
decodedHash, err := ocrypto.Base64Decode([]byte(segment.Hash))
if err != nil {
return fmt.Errorf("ocrypto.Base64Decode failed:%w", err)
}
aggregateHash.Write(decodedHash)
}
res, err := validateRootSignature(r.manifest, aggregateHash.Bytes(), payloadKey[:])
if err != nil {
return fmt.Errorf("%w: splitKey.validateRootSignature failed: %w", ErrRootSignatureFailure, err)
}
if !res {
return fmt.Errorf("%w: %w", ErrRootSignatureFailure, ErrRootSigValidation)
}
segSize := r.manifest.EncryptionInformation.IntegrityInformation.DefaultSegmentSize
encryptedSegSize := r.manifest.EncryptionInformation.IntegrityInformation.DefaultEncryptedSegSize
if segSize != encryptedSegSize-(gcmIvSize+aesBlockSize) {
return ErrSegSizeMismatch
}
// Validate assertions
for _, assertion := range r.manifest.Assertions {
// Skip assertion verification if disabled
if r.config.disableAssertionVerification {
continue
}
assertionKey := AssertionKey{}
// Set default to HS256
assertionKey.Alg = AssertionKeyAlgHS256
assertionKey.Key = payloadKey[:]
if !r.config.AssertionVerificationKeys.IsEmpty() {
// Look up the key for the assertion
foundKey, err := r.config.AssertionVerificationKeys.Get(assertion.ID)
if err != nil {
return fmt.Errorf("%w: %w", ErrAssertionFailure{ID: assertion.ID}, err)
} else if !foundKey.IsEmpty() {
assertionKey.Alg = foundKey.Alg
assertionKey.Key = foundKey.Key
}
}
assertionHash, assertionSig, err := assertion.Verify(assertionKey)
if err != nil {
if errors.Is(err, errAssertionVerifyKeyFailure) {
return fmt.Errorf("assertion verification failed: %w", err)
}
return fmt.Errorf("%w: assertion verification failed: %w", ErrAssertionFailure{ID: assertion.ID}, err)
}
// Get the hash of the assertion
hashOfAssertionAsHex, err := assertion.GetHash()
if err != nil {
return fmt.Errorf("%w: failed to get hash of assertion: %w", ErrAssertionFailure{ID: assertion.ID}, err)
}
hashOfAssertion := make([]byte, hex.DecodedLen(len(hashOfAssertionAsHex)))
_, err = hex.Decode(hashOfAssertion, hashOfAssertionAsHex)
if err != nil {
return fmt.Errorf("error decoding hex string: %w", err)
}
isLegacyTDF := r.manifest.TDFVersion == ""
if isLegacyTDF {
hashOfAssertion = hashOfAssertionAsHex
}
var completeHashBuilder bytes.Buffer
completeHashBuilder.Write(aggregateHash.Bytes())
completeHashBuilder.Write(hashOfAssertion)
base64Hash := ocrypto.Base64Encode(completeHashBuilder.Bytes())
if string(hashOfAssertionAsHex) != assertionHash {
return fmt.Errorf("%w: assertion hash missmatch", ErrAssertionFailure{ID: assertion.ID})
}
if assertionSig != string(base64Hash) {
return fmt.Errorf("%w: failed integrity check on assertion signature", ErrAssertionFailure{ID: assertion.ID})
}
}
var payloadSize int64
for _, seg := range r.manifest.EncryptionInformation.IntegrityInformation.Segments {
payloadSize += seg.Size
}
gcm, err := ocrypto.NewAESGcm(payloadKey[:])
if err != nil {
return fmt.Errorf("ocrypto.NewAESGcm failed:%w", err)
}
r.payloadSize = payloadSize
r.unencryptedMetadata = unencryptedMetadata
r.payloadKey = payloadKey[:]
r.aesGcm = gcm