-
Notifications
You must be signed in to change notification settings - Fork 2
/
mtc.go
1694 lines (1481 loc) · 36.2 KB
/
mtc.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 mtc
import (
"bytes"
"crypto"
"crypto/sha256"
"errors"
"fmt"
"io"
"net"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/crypto/cryptobyte"
)
// CAParams holds the public parameters of a Merkle Tree CA
type CAParams struct {
Issuer RelativeOID
PublicKey Verifier
ProofType ProofType
StartTime uint64
BatchDuration uint64
Lifetime uint64
ValidityWindowSize uint64
StorageWindowSize uint64
HttpServer string
}
const (
HashLen = 32
)
type ClaimType uint16
const (
DnsClaimType ClaimType = iota
DnsWildcardClaimType
Ipv4ClaimType
Ipv6ClaimType
)
// List of claims.
type Claims struct {
DNS []string
DNSWildcard []string
IPv4 []net.IP
IPv6 []net.IP
Unknown []UnknownClaim
}
// Represents a claim we do not how to interpret.
type UnknownClaim struct {
Type ClaimType
Info []byte
}
type SubjectType uint16
const (
TLSSubjectType SubjectType = iota
)
type SubjectBase interface {
Type() SubjectType
Info() []byte
}
type AbridgedSubject interface {
SubjectBase
}
type Subject interface {
SubjectBase
Abridge() AbridgedSubject
}
type TLSSubject struct {
pk Verifier
packed []byte
}
// Used for either an unknown (abridged) subject
type UnknownSubject struct {
typ SubjectType
info []byte
}
type Assertion struct {
Subject Subject
Claims Claims
}
type AbridgedAssertion struct {
Subject AbridgedSubject
Claims Claims
}
// Copy of tls.SignatureScheme to prevent cycling dependencies
type SignatureScheme uint16
const (
TLSPSSWithSHA256 SignatureScheme = 0x0804
TLSPSSWithSHA384 SignatureScheme = 0x0805
TLSPSSWithSHA512 SignatureScheme = 0x0806
TLSECDSAWithP256AndSHA256 SignatureScheme = 0x0403
TLSECDSAWithP384AndSHA384 SignatureScheme = 0x0503
TLSECDSAWithP521AndSHA512 SignatureScheme = 0x0603
TLSEd25519 SignatureScheme = 0x0807
// Just for testing we use ML-DSA-87 with a codepoint in the
// private use region.
// For production SLH-DSA-128s would be a better choice.
TLSMLDSA87 SignatureScheme = 0x0906
)
type AbridgedTLSSubject struct {
SignatureScheme SignatureScheme
PublicKeyHash [HashLen]byte
}
type BikeshedCertificate struct {
Assertion Assertion
Proof Proof
}
type ProofType uint16
const (
MerkleTreeProofType ProofType = iota
)
type Proof interface {
TrustAnchorIdentifier() TrustAnchorIdentifier
Info() []byte
}
type MerkleTreeProof struct {
anchor TrustAnchorIdentifier
index uint64
path []byte
}
type UnknownProof struct {
anchor TrustAnchorIdentifier
info []byte
}
type ValidityWindow struct {
BatchNumber uint32
TreeHeads []byte
}
type SignedValidityWindow struct {
ValidityWindow
Signature []byte
}
func (p *MerkleTreeProof) TrustAnchorIdentifier() TrustAnchorIdentifier {
return p.anchor
}
func (p *MerkleTreeProof) Info() []byte {
var b cryptobyte.Builder
b.AddUint64(p.index)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(p.path)
})
ret, err := b.Bytes()
if err != nil {
// Can only happen if path is too long, but we checked for this.
panic(err)
}
return ret
}
func (p *MerkleTreeProof) Path() []byte {
return p.path
}
func (p *MerkleTreeProof) Index() uint64 {
return p.index
}
func (p *UnknownProof) TrustAnchorIdentifier() TrustAnchorIdentifier {
return p.anchor
}
func (p *UnknownProof) Info() []byte {
return p.info
}
type Batch struct {
CA *CAParams
Number uint32
}
// Range of batch numbers Begin, …, End-1.
type BatchRange struct {
Begin uint32
End uint32
}
func (r BatchRange) Len() int {
return int(r.End) - int(r.Begin)
}
// Returns whether each batch in the range is after the given batch
func (r BatchRange) AreAllPast(batch uint32) bool {
if r.Begin == r.End {
return true
}
return batch < r.Begin
}
// Returns whether r contains the batch with the given number.
func (r BatchRange) Contains(batch uint32) bool {
return r.Begin <= batch && batch < r.End
}
func (r BatchRange) String() string {
if r.Begin == r.End {
return "⌀"
}
if r.End == r.Begin+1 {
return fmt.Sprintf("%d", r.Begin)
}
if r.End == r.Begin+2 {
return fmt.Sprintf("%d,%d", r.Begin, r.Begin+1)
}
return fmt.Sprintf("%d,…,%d", r.Begin, r.End-1)
}
// Merkle tree built upon the assertions of a batch.
type Tree struct {
// Concatenation of nodes left-to-right, bottom-to-top, so for
//
// level 2: t20
// _____/ \_____
// / \
// level 1: t10 t11
// / \ / \
// / \ / \
// level 0: t00 t01 t02 t03
// | | |
// a0 a1 a2
//
// we would have buf be the concatenation of t00 t01 t02 t03 t10 t11 t20.
buf []byte
nLeaves uint64 // Number of assertions
}
// Write the tree to w
func (t *Tree) WriteTo(w io.Writer) error {
var b cryptobyte.Builder
b.AddUint64(t.nLeaves)
buf, err := b.Bytes()
if err != nil {
return err
}
_, err = w.Write(buf)
if err != nil {
return err
}
_, err = w.Write(t.buf)
if err != nil {
return err
}
return nil
}
func (t *Tree) NodeCount() uint {
return TreeNodeCount(t.nLeaves)
}
// TreeNodeCount returns the number of nodes in the Merkle tree for a batch, which has
// nLeaves assertions.
func TreeNodeCount(nLeaves uint64) uint {
if nLeaves == 0 {
return 1
}
nodesInLayer := uint(nLeaves)
ret := uint(0)
for nodesInLayer != 1 {
if nodesInLayer&1 == 1 {
nodesInLayer++
}
ret += nodesInLayer
nodesInLayer >>= 1
}
ret++ // we didn't count the root yet
return ret
}
func (t *Tree) UnmarshalBinary(buf []byte) error {
s := cryptobyte.String(buf)
if !s.ReadUint64(&t.nLeaves) {
return ErrTruncated
}
nNodes := TreeNodeCount(t.nLeaves)
t.buf = make([]byte, int(nNodes)*HashLen)
if !s.CopyBytes(t.buf) {
return ErrTruncated
}
if !s.Empty() {
return ErrExtraBytes
}
return nil
}
func (c *BikeshedCertificate) MarshalBinary() ([]byte, error) {
var b cryptobyte.Builder
buf, err := c.Assertion.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("failed to marshal Assertion: %w", err)
}
b.AddBytes(buf)
buf, err = c.Proof.TrustAnchorIdentifier().MarshalBinary()
if err != nil {
return nil, fmt.Errorf("failed to marshal TAI: %w", err)
}
b.AddBytes(buf)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(c.Proof.Info())
})
return b.Bytes()
}
func (c *BikeshedCertificate) UnmarshalBinary(data []byte, caStore CAStore) error {
s := cryptobyte.String(data)
err := c.Assertion.unmarshal(&s)
if err != nil {
return fmt.Errorf("failed to unmarshal Assertion: %w", err)
}
var (
proofInfo cryptobyte.String
)
tai := TrustAnchorIdentifier{}
err = tai.unmarshal(&s)
if err != nil {
return fmt.Errorf("failed to unmarshal TrustAnchorIdentifier: %w", err)
}
if !s.ReadUint16LengthPrefixed(&proofInfo) {
return ErrTruncated
}
if !s.Empty() {
return ErrExtraBytes
}
switch tai.ProofType(caStore) {
case MerkleTreeProofType:
proof := &MerkleTreeProof{}
if !proofInfo.ReadUint64(&proof.index) ||
!copyUint16LengthPrefixed(&proofInfo, &proof.path) {
return ErrTruncated
}
if !proofInfo.Empty() {
return ErrExtraBytes
}
proof.anchor = tai
c.Proof = proof
return nil
}
c.Proof = &UnknownProof{
anchor: tai,
info: []byte(proofInfo),
}
return nil
}
// Batches that are expected to be available at this CA, at the given time.
// The last few might not yet have been published.
func (p *CAParams) StoredBatches(dt time.Time) BatchRange {
ts := dt.Unix()
if ts < int64(p.StartTime) {
return BatchRange{} // none
}
currentNumber := (ts - int64(p.StartTime)) / int64(p.BatchDuration)
start := currentNumber - int64(p.StorageWindowSize)
if start < 0 {
start = 0
}
return BatchRange{
Begin: uint32(start),
End: uint32(currentNumber),
}
}
// Returns the the time when the next batch starts.
func (p *CAParams) NextBatchAt(dt time.Time) time.Time {
ts := dt.Unix()
currentNumber := (ts - int64(p.StartTime)) / int64(p.BatchDuration)
if currentNumber < 0 {
return time.Unix(int64(p.StartTime), 0)
}
return time.Unix(
int64(p.StartTime+p.BatchDuration*uint64(currentNumber+1)),
0,
)
}
// Batches that are non-expired, and either issued or ready, at the given time.
func (p *CAParams) ActiveBatches(dt time.Time) BatchRange {
ts := dt.Unix()
if ts < int64(p.StartTime) {
return BatchRange{} // none
}
currentNumber := (ts - int64(p.StartTime)) / int64(p.BatchDuration)
start := currentNumber - int64(p.ValidityWindowSize)
if start < 0 {
start = 0
}
return BatchRange{
Begin: uint32(start),
End: uint32(currentNumber),
}
}
func (p *CAParams) MarshalBinary() ([]byte, error) {
// TODO add struct to I-D
var b cryptobyte.Builder
var issuer, err = p.Issuer.MarashalBinary()
if err != nil {
return nil, err
}
b.AddBytes(issuer)
b.AddUint16(uint16(p.PublicKey.Scheme()))
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(p.PublicKey.Bytes())
})
b.AddUint16(uint16(p.ProofType))
b.AddUint64(p.StartTime)
b.AddUint64(p.BatchDuration)
b.AddUint64(p.Lifetime)
b.AddUint64(p.ValidityWindowSize)
b.AddUint64(p.StorageWindowSize)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes([]byte(p.HttpServer))
})
return b.Bytes()
}
func (p *CAParams) UnmarshalBinary(data []byte) error {
s := cryptobyte.String(data)
var (
issuerBuf []byte
pkBuf []byte
httpServerBuf []byte
sigScheme SignatureScheme
err error
)
if !s.ReadUint8LengthPrefixed((*cryptobyte.String)(&issuerBuf)) ||
!s.ReadUint16((*uint16)(&sigScheme)) ||
!s.ReadUint16LengthPrefixed((*cryptobyte.String)(&pkBuf)) ||
!s.ReadUint16((*uint16)(&p.ProofType)) ||
!s.ReadUint64(&p.StartTime) ||
!s.ReadUint64(&p.BatchDuration) ||
!s.ReadUint64(&p.Lifetime) ||
!s.ReadUint64(&p.ValidityWindowSize) ||
!s.ReadUint64(&p.StorageWindowSize) ||
!s.ReadUint16LengthPrefixed((*cryptobyte.String)(&httpServerBuf)) {
return ErrTruncated
}
if !s.Empty() {
return ErrExtraBytes
}
p.Issuer = issuerBuf
p.HttpServer = string(httpServerBuf)
p.PublicKey, err = UnmarshalVerifier(sigScheme, pkBuf)
if err != nil {
return err
}
return p.Validate()
}
func (p *CAParams) Validate() error {
// If the issuer uses the full 255 bytes, there can be at most 128 batches,
// as there is only a single byte left for encoding the batch.
// TODO Maybe reduce the maximum allowed size of the issuer OID.
if len(p.Issuer) > 255 {
return errors.New("issuer must be 255 bytes or less")
}
if len(p.Issuer) == 0 {
return errors.New("issuer can't be empty")
}
if p.Lifetime%p.BatchDuration != 0 {
return errors.New("lifetime must be a multiple of batch_duration")
}
if p.ValidityWindowSize != p.Lifetime/p.BatchDuration {
return errors.New("validity_window_size ≠ lifetime / batch_duration")
}
if p.StorageWindowSize < 2*p.ValidityWindowSize {
return errors.New("storage_window_size < 2*validity_window_size")
}
return nil
}
// Returns the roots of the validity window prior the epoch.
func (p *CAParams) PreEpochRoots() []byte {
b := Batch{
Number: 0,
CA: p,
}
ret := make([]byte, int(p.ValidityWindowSize)*HashLen)
if err := b.hashEmpty(ret[:], 0, 0); err != nil {
panic(err)
}
for i := 1; i < int(p.ValidityWindowSize); i++ {
copy(ret[i*HashLen:(i+1)*HashLen], ret[0:HashLen])
}
return ret
}
func (w *ValidityWindow) unmarshal(s *cryptobyte.String, p *CAParams) error {
w.TreeHeads = make([]byte, int(HashLen*p.ValidityWindowSize))
if !s.ReadUint32(&w.BatchNumber) || !s.CopyBytes(w.TreeHeads) {
return ErrTruncated
}
return nil
}
func (w *SignedValidityWindow) UnmarshalBinary(data []byte, p *CAParams) error {
err := w.UnmarshalBinaryWithoutVerification(data, p)
if err != nil {
return err
}
toSign, err := w.ValidityWindow.LabeledValdityWindow(p)
if err != nil {
return err
}
return p.PublicKey.Verify(toSign, w.Signature)
}
// Like UnmarshalBinary() but doesn't check the signature.
func (w *SignedValidityWindow) UnmarshalBinaryWithoutVerification(
data []byte, p *CAParams) error {
s := cryptobyte.String(data)
err := w.ValidityWindow.unmarshal(&s, p)
if err != nil {
return err
}
if !copyUint16LengthPrefixed(&s, &w.Signature) {
return ErrTruncated
}
if !s.Empty() {
return ErrExtraBytes
}
return nil
}
func (w *ValidityWindow) MarshalBinary() ([]byte, error) {
var b cryptobyte.Builder
b.AddUint32(w.BatchNumber)
b.AddBytes(w.TreeHeads)
return b.Bytes()
}
func (w *SignedValidityWindow) MarshalBinary() ([]byte, error) {
var b cryptobyte.Builder
window, err := w.ValidityWindow.MarshalBinary()
if err != nil {
return nil, err
}
b.AddBytes(window)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(w.Signature)
})
return b.Bytes()
}
// Returns the corresponding marshalled LabeledValdityWindow, which
// is signed by the CA.
func (w *ValidityWindow) LabeledValdityWindow(ca *CAParams) ([]byte, error) {
var b cryptobyte.Builder
b.AddBytes([]byte("Merkle Tree Crts ValidityWindow\000"))
var issuer, err = ca.Issuer.MarashalBinary()
if err != nil {
return nil, err
}
b.AddBytes(issuer)
buf, err := w.MarshalBinary()
if err != nil {
return nil, err
}
b.AddBytes(buf)
return b.Bytes()
}
// Returns TreeHeads from the previous batch's TreeHeads and the new root.
func (p *CAParams) newTreeHeads(prevHeads, root []byte) ([]byte, error) {
expected := HashLen * p.ValidityWindowSize
if len(prevHeads) != int(expected) {
return nil, fmt.Errorf(
"Expected prevHeads to be %d bytes; got %d bytes instead",
expected,
len(prevHeads),
)
}
if len(root) != HashLen {
return nil, fmt.Errorf(
"Expected root to be %d bytes; got %d bytes instead",
expected,
len(root),
)
}
return append(prevHeads[HashLen:], root...), nil
}
func (batch *Batch) Anchor() TrustAnchorIdentifier {
tai := TrustAnchorIdentifier{
Issuer: batch.CA.Issuer,
BatchNumber: batch.Number,
}
return tai
}
func (batch *Batch) SignValidityWindow(signer Signer, prevHeads []byte,
root []byte) (SignedValidityWindow, error) {
newHeads, err := batch.CA.newTreeHeads(prevHeads, root)
if err != nil {
return SignedValidityWindow{}, err
}
w := SignedValidityWindow{
ValidityWindow: ValidityWindow{
BatchNumber: batch.Number,
TreeHeads: newHeads,
},
}
toSign, err := w.ValidityWindow.LabeledValdityWindow(batch.CA)
if err != nil {
return SignedValidityWindow{}, fmt.Errorf(
"computing LabeledValidityWindow: %w",
err,
)
}
w.Signature = signer.Sign(toSign)
return w, nil
}
func NewTLSSubject(scheme SignatureScheme, pk crypto.PublicKey) (*TLSSubject, error) {
ver, err := NewVerifier(scheme, pk)
if err != nil {
return nil, err
}
var b cryptobyte.Builder
b.AddUint16(uint16(scheme))
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(ver.Bytes())
})
packed, err := b.Bytes()
if err != nil {
return nil, err
}
return &TLSSubject{
pk: ver,
packed: packed,
}, nil
}
func (s *TLSSubject) Verifier() (Verifier, error) {
if s.pk != nil {
return s.pk, nil
}
ss := cryptobyte.String(s.packed)
var (
scheme SignatureScheme
publicKey cryptobyte.String
)
if !ss.ReadUint16((*uint16)(&scheme)) ||
!ss.ReadUint16LengthPrefixed(&publicKey) {
return nil, ErrTruncated
}
if !ss.Empty() {
return nil, ErrExtraBytes
}
pk, err := UnmarshalVerifier(scheme, []byte(publicKey))
if err != nil {
return nil, err
}
s.pk = pk
return pk, nil
}
func (p ProofType) String() string {
switch p {
case MerkleTreeProofType:
return "merkle_tree_sha256"
default:
return fmt.Sprintf("ProofType(%d)", p)
}
}
func (s SubjectType) String() string {
switch s {
case TLSSubjectType:
return "TLS"
default:
return fmt.Sprintf("SubjectType(%d)", s)
}
}
func (s *TLSSubject) Type() SubjectType { return TLSSubjectType }
func (s *TLSSubject) Info() []byte {
return s.packed
}
func (s *TLSSubject) Abridge() AbridgedSubject {
ss := cryptobyte.String(s.packed)
var (
scheme SignatureScheme
publicKey cryptobyte.String
)
if !ss.ReadUint16((*uint16)(&scheme)) ||
!ss.ReadUint16LengthPrefixed(&publicKey) {
panic(ErrTruncated)
}
return &AbridgedTLSSubject{
PublicKeyHash: sha256.Sum256([]byte(publicKey)),
SignatureScheme: scheme,
}
}
func (s *AbridgedTLSSubject) Type() SubjectType { return TLSSubjectType }
func (s *AbridgedTLSSubject) Info() []byte {
var b cryptobyte.Builder
b.AddUint16(uint16(s.SignatureScheme))
b.AddBytes(s.PublicKeyHash[:])
buf, _ := b.Bytes()
return buf
}
func (s *UnknownSubject) Type() SubjectType { return s.typ }
func (s *UnknownSubject) Info() []byte { return s.info }
func (s *UnknownSubject) Abridge() AbridgedSubject {
panic("Can't abridge unknown subject")
}
func (a *Assertion) Abridge() (ret AbridgedAssertion) {
ret.Claims = a.Claims
ret.Subject = a.Subject.Abridge()
return
}
func (a *Assertion) MarshalBinary() ([]byte, error) {
var b cryptobyte.Builder
b.AddUint16(uint16(a.Subject.Type()))
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { // subject_info
b.AddBytes(a.Subject.Info())
})
claims, err := a.Claims.MarshalBinary()
if err != nil {
return nil, err
}
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(claims)
})
return b.Bytes()
}
func (a *Assertion) UnmarshalBinary(data []byte) error {
s := cryptobyte.String(data)
err := a.unmarshal(&s)
if err != nil {
return err
}
if !s.Empty() {
return ErrExtraBytes
}
return nil
}
func (a *Assertion) unmarshal(s *cryptobyte.String) error {
var (
subjectType SubjectType
subjectInfo []byte
claims cryptobyte.String
)
if !s.ReadUint16((*uint16)(&subjectType)) ||
!copyUint16LengthPrefixed(s, &subjectInfo) ||
!s.ReadUint16LengthPrefixed(&claims) {
return ErrTruncated
}
if err := a.Claims.UnmarshalBinary([]byte(claims)); err != nil {
return fmt.Errorf("Failed to unmarshal claims: %w", err)
}
switch subjectType {
case TLSSubjectType:
a.Subject = &TLSSubject{
packed: subjectInfo,
}
default:
a.Subject = &UnknownSubject{
typ: subjectType,
info: subjectInfo,
}
}
return nil
}
func (a *AbridgedAssertion) maxSize() int {
return (65535+2)*2 + 2
}
func (a *AbridgedAssertion) MarshalBinary() ([]byte, error) {
var b cryptobyte.Builder
b.AddUint16(uint16(a.Subject.Type()))
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { // abridged_subject_info
b.AddBytes(a.Subject.Info())
})
claims, err := a.Claims.MarshalBinary()
if err != nil {
return nil, err
}
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(claims)
})
return b.Bytes()
}
func (a *AbridgedAssertion) UnmarshalBinary(data []byte) error {
s := cryptobyte.String(data)
err := a.unmarshal(&s)
if err != nil {
return err
}
if !s.Empty() {
return ErrExtraBytes
}
return nil
}
func (a *AbridgedAssertion) unmarshal(s *cryptobyte.String) error {
var (
subjectType SubjectType
subjectInfo cryptobyte.String
claims cryptobyte.String
)
if !s.ReadUint16((*uint16)(&subjectType)) ||
!s.ReadUint16LengthPrefixed(&subjectInfo) ||
!s.ReadUint16LengthPrefixed(&claims) {
return ErrTruncated
}
if err := a.Claims.UnmarshalBinary([]byte(claims)); err != nil {
return fmt.Errorf("Failed to unmarshal claims: %w", err)
}
switch subjectType {
case TLSSubjectType:
var subject AbridgedTLSSubject
if !subjectInfo.ReadUint16((*uint16)(&subject.SignatureScheme)) ||
!subjectInfo.CopyBytes(subject.PublicKeyHash[:]) {
return ErrTruncated
}
if !subjectInfo.Empty() {
return ErrExtraBytes
}
a.Subject = &subject
default:
subjectInfoBuf := make([]byte, len(subjectInfo))
copy(subjectInfoBuf, subjectInfo)
a.Subject = &UnknownSubject{
typ: subjectType,
info: subjectInfoBuf,
}
}
return nil
}
func (t *Tree) LeafCount() uint64 {
return t.nLeaves
}
// Return root of the tree
func (t *Tree) Root() []byte {
return t.buf[len(t.buf)-HashLen : len(t.buf)]
}
// Return authentication path proving that the leaf at the given index
// is included in the Merkle tree.
func (t *Tree) AuthenticationPath(index uint64) ([]byte, error) {
if index >= t.nLeaves {
return nil, errors.New("Tree index out of range")
}
ret := bytes.Buffer{}
offset := 0
nNodes := t.nLeaves
for nNodes != 1 {
index ^= 1 // index of sibling
start := offset + int(HashLen*index)
_, _ = ret.Write(t.buf[start : start+HashLen])
// Account for the empty node
if nNodes&1 == 1 {
nNodes++
}
offset += HashLen * int(nNodes)
index >>= 1
nNodes >>= 1
}
return ret.Bytes(), nil
}
// Reads a stream of AbridgedAssertions from in, hashes them, and
// returns the concatenated hashes.
func (batch *Batch) hashLeaves(r io.Reader) ([]byte, error) {
ret := &bytes.Buffer{}
// First read all abridged assertions and hash them.
var index uint64
hash := make([]byte, HashLen)
err := unmarshal(r, func(_ int, aa *AbridgedAssertion) error {
err := aa.Hash(hash, batch, index)
if err != nil {
return err
}
_, _ = ret.Write(hash)
index++
return nil
})
if err != nil {
return nil, err
}
return ret.Bytes(), nil
}
// Unmarshals AbridgedAssertions from r and calls f for each, with
// the offset in the stream as first argument, and the abridged
// assertion as second argument.
//
// Returns early one rror.
func UnmarshalAbridgedAssertions(r io.Reader,
f func(int, *AbridgedAssertion) error) error {
return unmarshal(r, f)
}
// Compute batch root from authentication path.
//
// To verify a certificate/proof, use VerifyAuthenticationPath instead.
func (batch *Batch) ComputeRootFromAuthenticationPath(index uint64,
path []byte, aa *AbridgedAssertion) ([]byte, error) {
h := make([]byte, HashLen)
if err := aa.Hash(h[:], batch, index); err != nil {
return nil, err
}
level := uint8(0)
var left, right []byte
for len(path) != 0 {
if len(path) < HashLen {
return nil, ErrTruncated
}
left, right, path = h, path[:HashLen], path[HashLen:]
if index&1 == 1 {
left, right = right, left
}
level++
index >>= 1
_ = batch.hashNode(h, left, right, index, level)
}
if index != 0 {
return nil, fmt.Errorf("Authentication path too short")
}