-
Notifications
You must be signed in to change notification settings - Fork 26
/
headers.go
713 lines (664 loc) · 20.9 KB
/
headers.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
package cose
import (
"errors"
"fmt"
"math/big"
"strings"
"github.com/fxamacker/cbor/v2"
)
// COSE Header labels registered in the IANA "COSE Header Parameters" registry.
//
// Reference: https://www.iana.org/assignments/cose/cose.xhtml#header-parameters
const (
HeaderLabelAlgorithm int64 = 1
HeaderLabelCritical int64 = 2
HeaderLabelContentType int64 = 3
HeaderLabelKeyID int64 = 4
HeaderLabelIV int64 = 5
HeaderLabelPartialIV int64 = 6
HeaderLabelCounterSignature int64 = 7
HeaderLabelCounterSignature0 int64 = 9
HeaderLabelCounterSignatureV2 int64 = 11
HeaderLabelCounterSignature0V2 int64 = 12
HeaderLabelCWTClaims int64 = 15
HeaderLabelType int64 = 16
HeaderLabelX5Bag int64 = 32
HeaderLabelX5Chain int64 = 33
HeaderLabelX5T int64 = 34
HeaderLabelX5U int64 = 35
)
// ProtectedHeader contains parameters that are to be cryptographically
// protected.
type ProtectedHeader map[any]any
// MarshalCBOR encodes the protected header into a CBOR bstr object.
// A zero-length header is encoded as a zero-length string rather than as a
// zero-length map (encoded as h'a0').
func (h ProtectedHeader) MarshalCBOR() ([]byte, error) {
var encoded []byte
if len(h) == 0 {
encoded = []byte{}
} else {
err := validateHeaderParameters(h, true)
if err != nil {
return nil, fmt.Errorf("protected header: %w", err)
}
encoded, err = encMode.Marshal(map[any]any(h))
if err != nil {
return nil, err
}
}
return encMode.Marshal(encoded)
}
// UnmarshalCBOR decodes a CBOR bstr object into ProtectedHeader.
//
// ProtectedHeader is an empty_or_serialized_map where
//
// empty_or_serialized_map = bstr .cbor header_map / bstr .size 0
func (h *ProtectedHeader) UnmarshalCBOR(data []byte) error {
if h == nil {
return errors.New("cbor: UnmarshalCBOR on nil ProtectedHeader pointer")
}
var encoded byteString
if err := encoded.UnmarshalCBOR(data); err != nil {
return err
}
if encoded == nil {
return errors.New("cbor: nil protected header")
}
if len(encoded) == 0 {
*h = make(ProtectedHeader)
} else {
if encoded[0]>>5 != 5 { // major type 5: map
return errors.New("cbor: protected header: require map type")
}
if err := validateHeaderLabelCBOR(encoded); err != nil {
return err
}
var header map[any]any
if err := decMode.Unmarshal(encoded, &header); err != nil {
return err
}
candidate := ProtectedHeader(header)
if err := validateHeaderParameters(candidate, true); err != nil {
return fmt.Errorf("protected header: %w", err)
}
// cast to type Algorithm if `alg` presents
if alg, err := candidate.Algorithm(); err == nil {
candidate.SetAlgorithm(alg)
}
*h = candidate
}
return nil
}
// SetAlgorithm sets the algorithm value of the protected header.
func (h ProtectedHeader) SetAlgorithm(alg Algorithm) {
h[HeaderLabelAlgorithm] = alg
}
// SetType sets the type of the cose object in the protected header.
func (h ProtectedHeader) SetType(typ any) (any, error) {
if !canTstr(typ) && !canUint(typ) {
return typ, errors.New("header parameter: type: require tstr / uint type")
}
h[HeaderLabelType] = typ
return typ, nil
}
// SetCWTClaims sets the CWT Claims value of the protected header.
func (h ProtectedHeader) SetCWTClaims(claims CWTClaims) (CWTClaims, error) {
iss, hasIss := claims[1]
if hasIss && !canTstr(iss) {
return claims, errors.New("cwt claim: iss: require tstr")
}
sub, hasSub := claims[2]
if hasSub && !canTstr(sub) {
return claims, errors.New("cwt claim: sub: require tstr")
}
// TODO: validate claims, other claims
h[HeaderLabelCWTClaims] = claims
return claims, nil
}
// Algorithm gets the algorithm value from the algorithm header.
func (h ProtectedHeader) Algorithm() (Algorithm, error) {
value, ok := h[HeaderLabelAlgorithm]
if !ok {
return 0, ErrAlgorithmNotFound
}
switch alg := value.(type) {
case Algorithm:
return alg, nil
case int:
return Algorithm(alg), nil
case int8:
return Algorithm(alg), nil
case int16:
return Algorithm(alg), nil
case int32:
return Algorithm(alg), nil
case int64:
return Algorithm(alg), nil
case string:
return AlgorithmReserved, fmt.Errorf("Algorithm(%q)", alg)
default:
return AlgorithmReserved, ErrInvalidAlgorithm
}
}
// Critical indicates which protected header labels an application that is
// processing a message is required to understand.
//
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-3.1
func (h ProtectedHeader) Critical() ([]any, error) {
value, ok := h[HeaderLabelCritical]
if !ok {
return nil, nil
}
err := ensureCritical(value, h)
if err != nil {
return nil, err
}
return value.([]any), nil
}
// ensureCritical ensures all critical headers are present in the protected bucket.
func ensureCritical(value any, headers map[any]any) error {
labels, ok := value.([]any)
if !ok {
return errors.New("invalid crit header")
}
// if present, the array MUST have at least one value in it.
if len(labels) == 0 {
return errors.New("empty crit header")
}
for _, label := range labels {
if !canInt(label) && !canTstr(label) {
return fmt.Errorf("require int / tstr type, got '%T': %v", label, label)
}
if _, ok := headers[label]; !ok {
return fmt.Errorf("missing critical header: %v", label)
}
}
return nil
}
// UnprotectedHeader contains parameters that are not cryptographically
// protected.
type UnprotectedHeader map[any]any
// MarshalCBOR encodes the unprotected header into a CBOR map object.
// A zero-length header is encoded as a zero-length map (encoded as h'a0').
func (h UnprotectedHeader) MarshalCBOR() ([]byte, error) {
if len(h) == 0 {
return []byte{0xa0}, nil
}
if err := validateHeaderParameters(h, false); err != nil {
return nil, fmt.Errorf("unprotected header: %w", err)
}
return encMode.Marshal(map[any]any(h))
}
// UnmarshalCBOR decodes a CBOR map object into UnprotectedHeader.
//
// UnprotectedHeader is a header_map.
func (h *UnprotectedHeader) UnmarshalCBOR(data []byte) error {
if h == nil {
return errors.New("cbor: UnmarshalCBOR on nil UnprotectedHeader pointer")
}
if data == nil {
return errors.New("cbor: nil unprotected header")
}
if len(data) == 0 {
return errors.New("cbor: unprotected header: missing type")
}
if data[0]>>5 != 5 { // major type 5: map
return errors.New("cbor: unprotected header: require map type")
}
if err := validateHeaderLabelCBOR(data); err != nil {
return err
}
// In order to unmarshal Countersignature structs, it is required to make it
// in two steps instead of one.
var partialHeader map[any]cbor.RawMessage
if err := decMode.Unmarshal(data, &partialHeader); err != nil {
return err
}
header := make(map[any]any, len(partialHeader))
for k, v := range partialHeader {
v, err := unmarshalUnprotected(k, v)
if err != nil {
return err
}
header[k] = v
}
if err := validateHeaderParameters(header, false); err != nil {
return fmt.Errorf("unprotected header: %w", err)
}
*h = header
return nil
}
// unmarshalUnprotected produces known structs such as counter signature
// headers, otherwise it defaults to regular unmarshaling to simple types.
func unmarshalUnprotected(key any, value cbor.RawMessage) (any, error) {
label, ok := normalizeLabel(key)
if ok {
switch label {
case HeaderLabelCounterSignature, HeaderLabelCounterSignatureV2:
return unmarshalAsCountersignature(value)
default:
}
}
return unmarshalAsAny(value)
}
// unmarshalAsCountersignature produces a Countersignature struct or a list of
// Countersignatures.
func unmarshalAsCountersignature(value cbor.RawMessage) (any, error) {
var result1 Countersignature
err := decMode.Unmarshal(value, &result1)
if err == nil {
return &result1, nil
}
var result2 []*Countersignature
err = decMode.Unmarshal(value, &result2)
if err == nil {
return result2, nil
}
return nil, errors.New("invalid Countersignature object / list of objects")
}
// unmarshalAsAny produces simple types.
func unmarshalAsAny(value cbor.RawMessage) (any, error) {
var result any
err := decMode.Unmarshal(value, &result)
if err != nil {
return nil, err
}
return result, nil
}
// Headers represents "two buckets of information that are not
// considered to be part of the payload itself, but are used for
// holding information about content, algorithms, keys, or evaluation
// hints for the processing of the layer."
//
// It is represented by CDDL fragments:
//
// Headers = (
// protected : empty_or_serialized_map,
// unprotected : header_map
// )
//
// header_map = {
// Generic_Headers,
// * label => values
// }
//
// label = int / tstr
// values = any
//
// empty_or_serialized_map = bstr .cbor header_map / bstr .size 0
//
// # See Also
//
// https://tools.ietf.org/html/rfc8152#section-3
type Headers struct {
// RawProtected contains the raw CBOR encoded data for the protected header.
// It is populated when decoding.
// Applications can use this field for customized encoding / decoding of
// the protected header in case the default decoder provided by this library
// is not preferred.
RawProtected cbor.RawMessage
// Protected contains parameters that are to be cryptographically protected.
// When encoding or signing, the protected header is encoded using the
// default CBOR encoder if RawProtected is set to nil. Otherwise,
// RawProtected will be used with Protected ignored.
Protected ProtectedHeader
// RawUnprotected contains the raw CBOR encoded data for the unprotected
// header. It is populated when decoding.
// Applications can use this field for customized encoding / decoding of
// the unprotected header in case the default decoder provided by this
// library is not preferred.
RawUnprotected cbor.RawMessage
// Unprotected contains parameters that are not cryptographically protected.
// When encoding, the unprotected header is encoded using the default CBOR
// encoder if RawUnprotected is set to nil. Otherwise, RawUnprotected will
// be used with Unprotected ignored.
Unprotected UnprotectedHeader
}
// marshal encoded both headers.
// It returns RawProtected and RawUnprotected if those are set.
func (h *Headers) marshal() (cbor.RawMessage, cbor.RawMessage, error) {
if err := h.ensureIV(); err != nil {
return nil, nil, err
}
protected, err := h.MarshalProtected()
if err != nil {
return nil, nil, err
}
unprotected, err := h.MarshalUnprotected()
if err != nil {
return nil, nil, err
}
return protected, unprotected, nil
}
// MarshalProtected encodes the protected header.
// RawProtected is returned if it is not set to nil.
func (h *Headers) MarshalProtected() ([]byte, error) {
if len(h.RawProtected) > 0 {
return h.RawProtected, nil
}
return encMode.Marshal(h.Protected)
}
// MarshalUnprotected encodes the unprotected header.
// RawUnprotected is returned if it is not set to nil.
func (h *Headers) MarshalUnprotected() ([]byte, error) {
if len(h.RawUnprotected) > 0 {
return h.RawUnprotected, nil
}
return encMode.Marshal(h.Unprotected)
}
// UnmarshalFromRaw decodes Protected from RawProtected and Unprotected from
// RawUnprotected.
func (h *Headers) UnmarshalFromRaw() error {
if err := decMode.Unmarshal(h.RawProtected, &h.Protected); err != nil {
return fmt.Errorf("cbor: invalid protected header: %w", err)
}
if err := decMode.Unmarshal(h.RawUnprotected, &h.Unprotected); err != nil {
return fmt.Errorf("cbor: invalid unprotected header: %w", err)
}
if err := h.ensureIV(); err != nil {
return err
}
return nil
}
// ensureSigningAlgorithm ensures the presence of the `alg` header if there is
// no externally supplied data for signing.
//
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-4.4
func (h *Headers) ensureSigningAlgorithm(alg Algorithm, external []byte) error {
candidate, err := h.Protected.Algorithm()
switch err {
case nil:
if candidate != alg {
return fmt.Errorf("%w: signer %v: header %v", ErrAlgorithmMismatch, alg, candidate)
}
return nil
case ErrAlgorithmNotFound:
if len(external) > 0 {
return nil
}
if h.RawProtected != nil {
return ErrAlgorithmNotFound
}
if h.Protected == nil {
h.Protected = make(ProtectedHeader)
}
h.Protected.SetAlgorithm(alg)
return nil
}
return err
}
// ensureVerificationAlgorithm ensures the presence of the `alg` header if there
// is no externally supplied data for verification.
//
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-4.4
func (h *Headers) ensureVerificationAlgorithm(alg Algorithm, external []byte) error {
candidate, err := h.Protected.Algorithm()
switch err {
case nil:
if candidate != alg {
return fmt.Errorf("%w: verifier %v: header %v", ErrAlgorithmMismatch, alg, candidate)
}
return nil
case ErrAlgorithmNotFound:
if len(external) > 0 {
return nil
}
}
return err
}
// ensureIV ensures IV and Partial IV are not both present
// in the protected and unprotected headers.
// It does not check if they are both present within one header,
// as it will be checked later on.
//
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-3.1
func (h *Headers) ensureIV() error {
if hasLabel(h.Protected, HeaderLabelIV) && hasLabel(h.Unprotected, HeaderLabelPartialIV) {
return errors.New("IV (protected) and PartialIV (unprotected) parameters must not both be present")
}
if hasLabel(h.Protected, HeaderLabelPartialIV) && hasLabel(h.Unprotected, HeaderLabelIV) {
return errors.New("IV (unprotected) and PartialIV (protected) parameters must not both be present")
}
return nil
}
// hasLabel returns true if h contains label.
func hasLabel(h map[any]any, label any) bool {
_, ok := h[label]
return ok
}
// validateHeaderParameters validates all headers conform to the spec.
func validateHeaderParameters(h map[any]any, protected bool) error {
existing := make(map[any]struct{}, len(h))
for label, value := range h {
// Validate that all header labels are integers or strings.
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-1.4
label, ok := normalizeLabel(label)
if !ok {
return errors.New("header label: require int / tstr type")
}
// Validate that there are no duplicated labels.
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-3
if _, ok := existing[label]; ok {
return fmt.Errorf("header label: duplicated label: %v", label)
} else {
existing[label] = struct{}{}
}
// Validate the generic parameters.
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-3.1
switch label {
case HeaderLabelAlgorithm:
_, isAlg := value.(Algorithm)
if !isAlg && !canInt(value) && !canTstr(value) {
return errors.New("header parameter: alg: require int / tstr type")
}
case HeaderLabelCritical:
if !protected {
return errors.New("header parameter: crit: not allowed")
}
if err := ensureCritical(value, h); err != nil {
return fmt.Errorf("header parameter: crit: %w", err)
}
case HeaderLabelType:
isTstr := canTstr(value)
if !isTstr && !canUint(value) {
return errors.New("header parameter: type: require tstr / uint type")
}
if isTstr {
v := value.(string)
if len(v) == 0 {
return errors.New("header parameter: type: require non-empty string")
}
if v[0] == ' ' || v[len(v)-1] == ' ' {
return errors.New("header parameter: type: require no leading/trailing whitespace")
}
// Basic check that the content type is of form type/subtype.
// We don't check the precise definition though (RFC 6838 Section 4.2).
if strings.Count(v, "/") != 1 {
return errors.New("header parameter: type: require text of form type/subtype")
}
}
case HeaderLabelContentType:
isTstr := canTstr(value)
if !isTstr && !canUint(value) {
return errors.New("header parameter: content type: require tstr / uint type")
}
if isTstr {
v := value.(string)
if len(v) == 0 {
return errors.New("header parameter: content type: require non-empty string")
}
if v[0] == ' ' || v[len(v)-1] == ' ' {
return errors.New("header parameter: content type: require no leading/trailing whitespace")
}
// Basic check that the content type is of form type/subtype.
// We don't check the precise definition though (RFC 6838 Section 4.2).
if strings.Count(v, "/") != 1 {
return errors.New("header parameter: content type: require text of form type/subtype")
}
}
case HeaderLabelKeyID:
if !canBstr(value) {
return errors.New("header parameter: kid: require bstr type")
}
case HeaderLabelIV:
if !canBstr(value) {
return errors.New("header parameter: IV: require bstr type")
}
if hasLabel(h, HeaderLabelPartialIV) {
return errors.New("header parameter: IV and PartialIV: parameters must not both be present")
}
case HeaderLabelPartialIV:
if !canBstr(value) {
return errors.New("header parameter: Partial IV: require bstr type")
}
if hasLabel(h, HeaderLabelIV) {
return errors.New("header parameter: IV and PartialIV: parameters must not both be present")
}
case HeaderLabelCounterSignature:
if protected {
return errors.New("header parameter: counter signature: not allowed")
}
if _, ok := value.(*Countersignature); !ok {
if _, ok := value.([]*Countersignature); !ok {
return errors.New("header parameter: counter signature is not a Countersignature or a list")
}
}
case HeaderLabelCounterSignature0:
if protected {
return errors.New("header parameter: countersignature0: not allowed")
}
if !canBstr(value) {
return errors.New("header parameter: countersignature0: require bstr type")
}
case HeaderLabelCounterSignatureV2:
if protected {
return errors.New("header parameter: Countersignature version 2: not allowed")
}
if _, ok := value.(*Countersignature); !ok {
if _, ok := value.([]*Countersignature); !ok {
return errors.New("header parameter: Countersignature version 2 is not a Countersignature or a list")
}
}
case HeaderLabelCounterSignature0V2:
if protected {
return errors.New("header parameter: Countersignature0 version 2: not allowed")
}
if !canBstr(value) {
return errors.New("header parameter: Countersignature0 version 2: require bstr type")
}
}
}
return nil
}
// canUint reports whether v can be used as a CBOR uint type.
func canUint(v any) bool {
switch v := v.(type) {
case uint, uint8, uint16, uint32, uint64:
return true
case int:
return v >= 0
case int8:
return v >= 0
case int16:
return v >= 0
case int32:
return v >= 0
case int64:
return v >= 0
}
return false
}
// canInt reports whether v can be used as a CBOR int type.
func canInt(v any) bool {
switch v.(type) {
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
return true
}
return false
}
// canTstr reports whether v can be used as a CBOR tstr type.
func canTstr(v any) bool {
_, ok := v.(string)
return ok
}
// canBstr reports whether v can be used as a CBOR bstr type.
func canBstr(v any) bool {
_, ok := v.([]byte)
return ok
}
// normalizeLabel tries to cast label into a int64 or a string.
// Returns (nil, false) if the label type is not valid.
func normalizeLabel(label any) (any, bool) {
switch v := label.(type) {
case int:
label = int64(v)
case int8:
label = int64(v)
case int16:
label = int64(v)
case int32:
label = int64(v)
case int64:
label = int64(v)
case uint:
label = int64(v)
case uint8:
label = int64(v)
case uint16:
label = int64(v)
case uint32:
label = int64(v)
case uint64:
label = int64(v)
case string:
// no conversion
default:
return nil, false
}
return label, true
}
// headerLabelValidator is used to validate the header label of a COSE header.
type headerLabelValidator struct {
value any
}
// String prints the value without brackets `{}`. Useful in error printing.
func (hlv headerLabelValidator) String() string {
return fmt.Sprint(hlv.value)
}
// UnmarshalCBOR decodes the label value of a COSE header, and returns error if
// label is not a int (major type 0, 1) or string (major type 3).
func (hlv *headerLabelValidator) UnmarshalCBOR(data []byte) error {
if len(data) == 0 {
return errors.New("cbor: header label: missing type")
}
switch data[0] >> 5 {
case 0, 1, 3:
err := decMode.Unmarshal(data, &hlv.value)
if err != nil {
return err
}
if _, ok := hlv.value.(big.Int); ok {
return errors.New("cbor: header label: int key must not be higher than 1<<63 - 1")
}
return nil
}
return errors.New("cbor: header label: require int / tstr type")
}
// discardedCBORMessage is used to read CBOR message and discard it.
type discardedCBORMessage struct{}
// UnmarshalCBOR discards the read CBOR object.
func (discardedCBORMessage) UnmarshalCBOR(data []byte) error {
return nil
}
// validateHeaderLabelCBOR validates if all header labels are integers or
// strings of a CBOR map object.
//
// label = int / tstr
//
// Reference: https://datatracker.ietf.org/doc/html/rfc8152#section-1.4
func validateHeaderLabelCBOR(data []byte) error {
var header map[headerLabelValidator]discardedCBORMessage
return decMode.Unmarshal(data, &header)
}