Debian Codegraph @

signature/cose/envelope.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package cose
15
16 import (
17 "crypto"
18 "crypto/rand"
19 "crypto/x509"
20 "errors"
21 "fmt"
22 "io"
23 "strconv"
24 "time"
25
26 "github.com/fxamacker/cbor/v2"
27 "github.com/notaryproject/notation-core-go/internal/timestamp"
28 "github.com/notaryproject/notation-core-go/signature"
29 "github.com/notaryproject/notation-core-go/signature/internal/base"
30 "github.com/notaryproject/tspclient-go"
31 "github.com/veraison/go-cose"
32 )
33
34 // MediaTypeEnvelope is the COSE signature envelope blob mediaType.
35 const MediaTypeEnvelope = "application/cose"
36
37 var (
38 // encMode is the encoding mode used in Sign
39 encMode cbor.EncMode
40
41 // decMode is the decoding mode used in Content
42 decMode cbor.DecMode
43 )
44
45 func init() {
46 err := signature.RegisterEnvelopeType(MediaTypeEnvelope, NewEnvelope, ParseEnvelope)
47 if err != nil {
48 panic(err)
49 }
50
51 encOpts := cbor.EncOptions{
52 Time: cbor.TimeUnix,
53 TimeTag: cbor.EncTagRequired,
54 }
55 encMode, err = encOpts.EncMode()
56 if err != nil {
57 panic(err)
58 }
59
60 decOpts := cbor.DecOptions{
61 TimeTag: cbor.DecTagRequired,
62 }
63 decMode, err = decOpts.DecMode()
64 if err != nil {
65 panic(err)
66 }
67 }
68
69 // Protected Headers
70 // https://github.com/notaryproject/notaryproject/blob/cose-envelope/signature-envelope-cose.md
71 const (
72 headerLabelExpiry = "io.cncf.notary.expiry"
73 headerLabelSigningScheme = "io.cncf.notary.signingScheme"
74 headerLabelSigningTime = "io.cncf.notary.signingTime"
75 headerLabelAuthenticSigningTime = "io.cncf.notary.authenticSigningTime"
76 )
77
78 // Unprotected Headers
79 // https://github.com/notaryproject/notaryproject/blob/cose-envelope/signature-envelope-cose.md
80 const (
81 headerLabelTimestampSignature = "io.cncf.notary.timestampSignature"
82 headerLabelSigningAgent = "io.cncf.notary.signingAgent"
83 )
84
85 // Map of cose.Algorithm to signature.Algorithm
86 var coseAlgSignatureAlgMap = map[cose.Algorithm]signature.Algorithm{
87 cose.AlgorithmPS256: signature.AlgorithmPS256,
88 cose.AlgorithmPS384: signature.AlgorithmPS384,
89 cose.AlgorithmPS512: signature.AlgorithmPS512,
90 cose.AlgorithmES256: signature.AlgorithmES256,
91 cose.AlgorithmES384: signature.AlgorithmES384,
92 cose.AlgorithmES512: signature.AlgorithmES512,
93 }
94
95 // Map of signingScheme to signingTime header label
96 var signingSchemeTimeLabelMap = map[signature.SigningScheme]string{
97 signature.SigningSchemeX509: headerLabelSigningTime,
98 signature.SigningSchemeX509SigningAuthority: headerLabelAuthenticSigningTime,
99 }
100
101 // signer interface is a cose.Signer with certificate chain fetcher.
102 type signer interface {
103 cose.Signer
104 CertificateChain() []*x509.Certificate
105 }
106
107 // remoteSigner implements signer interface.
108 // It is used in Sign process when base's Sign implementation is desired.
109 type remoteSigner struct {
110 base signature.Signer
111 alg cose.Algorithm
112 certs []*x509.Certificate
113 }
114
115 func newRemoteSigner(base signature.Signer) (*remoteSigner, error) {
116 keySpec, err := base.KeySpec()
117 if err != nil {
118 return nil, err
119 }
120 alg, err := getSignatureAlgorithmFromKeySpec(keySpec)
121 if err != nil {
122 return nil, err
123 }
124 return &remoteSigner{
125 base: base,
126 alg: alg,
127 }, nil
128 }
129
130 // Algorithm implements cose.Signer interface.
131 func (signer *remoteSigner) Algorithm() cose.Algorithm {
132 return signer.alg
133 }
134
135 // Sign implements cose.Signer interface.
136 func (signer *remoteSigner) Sign(rand io.Reader, payload []byte) ([]byte, error) {
137 signature, certs, err := signer.base.Sign(payload)
138 if err != nil {
139 return nil, err
140 }
141 signer.certs = certs
142 return signature, nil
143 }
144
145 // CertificateChain implements signer interface.
146 func (signer *remoteSigner) CertificateChain() []*x509.Certificate {
147 return signer.certs
148 }
149
150 type localSigner struct {
151 cose.Signer
152 certs []*x509.Certificate
153 }
154
155 func newLocalSigner(base signature.LocalSigner) (*localSigner, error) {
156 key := base.PrivateKey()
157 if cryptoSigner, ok := key.(crypto.Signer); ok {
158 certs, err := base.CertificateChain()
159 if err != nil {
160 return nil, err
161 }
162 keySpec, err := base.KeySpec()
163 if err != nil {
164 return nil, err
165 }
166 alg, err := getSignatureAlgorithmFromKeySpec(keySpec)
167 if err != nil {
168 return nil, err
169 }
170 coseSigner, err := cose.NewSigner(alg, cryptoSigner)
171 if err != nil {
172 return nil, err
173 }
174 return &localSigner{
175 Signer: coseSigner,
176 certs: certs,
177 }, nil
178 }
179 return nil, &signature.UnsupportedSigningKeyError{}
180 }
181
182 // CertificateChain implements signer interface.
183 func (signer *localSigner) CertificateChain() []*x509.Certificate {
184 return signer.certs
185 }
186
187 type envelope struct {
188 base *cose.Sign1Message
189 }
190
191 // NewEnvelope initializes an empty COSE signature envelope.
192 func NewEnvelope() signature.Envelope {
193 return &base.Envelope{
194 Envelope: &envelope{},
195 }
196 }
197
198 // ParseEnvelope parses envelopeBytes to a COSE signature envelope.
199 func ParseEnvelope(envelopeBytes []byte) (signature.Envelope, error) {
200 var msg cose.Sign1Message
201 if err := msg.UnmarshalCBOR(envelopeBytes); err != nil {
202 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
203 }
204 return &base.Envelope{
205 Envelope: &envelope{
206 base: &msg,
207 },
208 Raw: envelopeBytes,
209 }, nil
210 }
211
212 // Sign implements signature.Envelope interface.
213 // On success, this function returns the COSE signature envelope byte slice.
214 func (e *envelope) Sign(req *signature.SignRequest) ([]byte, error) {
215 // get built-in signer from go-cose or remote signer based on req.Signer
216 signer, err := getSigner(req.Signer)
217 if err != nil {
218 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
219 }
220
221 // prepare COSE_Sign1 message
222 msg := cose.NewSign1Message()
223
224 // generate protected headers of COSE envelope
225 msg.Headers.Protected.SetAlgorithm(signer.Algorithm())
226 if err := generateProtectedHeaders(req, msg.Headers.Protected); err != nil {
227 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
228 }
229
230 // generate payload of COSE envelope
231 msg.Headers.Protected[cose.HeaderLabelContentType] = req.Payload.ContentType
232 msg.Payload = req.Payload.Content
233
234 // core sign process, generate signature of COSE envelope
235 if err := msg.Sign(rand.Reader, nil, signer); err != nil {
236 return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
237 }
238
239 // generate unprotected headers of COSE envelope.
240 generateUnprotectedHeaders(req, signer, msg.Headers.Unprotected)
241
242 // timestamping
243 if req.SigningScheme == signature.SigningSchemeX509 && req.Timestamper != nil {
244 hash, err := hashFromCOSEAlgorithm(signer.Algorithm())
245 if err != nil {
246 return nil, &signature.TimestampError{Detail: err}
247 }
248 timestampOpts := tspclient.RequestOptions{
249 Content: msg.Signature,
250 HashAlgorithm: hash,
251 }
252 timestampToken, err := timestamp.Timestamp(req, timestampOpts)
253 if err != nil {
254 return nil, &signature.TimestampError{Detail: err}
255 }
256 // on success, embed the timestamp token to Unprotected header
257 msg.Headers.Unprotected[headerLabelTimestampSignature] = timestampToken
258 }
259
260 // encode Sign1Message into COSE_Sign1_Tagged object
261 encoded, err := msg.MarshalCBOR()
262 if err != nil {
263 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
264 }
265 e.base = msg
266
267 return encoded, nil
268 }
269
270 // Verify implements signature.Envelope interface.
271 // Note: Verfiy only verifies integrity of the given COSE envelope.
272 func (e *envelope) Verify() (*signature.EnvelopeContent, error) {
273 // sanity check
274 if e.base == nil {
275 return nil, &signature.SignatureEnvelopeNotFoundError{}
276 }
277
278 certs, ok := e.base.Headers.Unprotected[cose.HeaderLabelX5Chain].([]any)
279 if !ok || len(certs) == 0 {
280 return nil, &signature.InvalidSignatureError{Msg: "certificate chain is not present"}
281 }
282 certRaw, ok := certs[0].([]byte)
283 if !ok {
284 return nil, &signature.InvalidSignatureError{Msg: "COSE envelope malformed leaf certificate"}
285 }
286 cert, err := x509.ParseCertificate(certRaw)
287 if err != nil {
288 return nil, &signature.InvalidSignatureError{Msg: "malformed leaf certificate"}
289 }
290
291 // core verify process, verify integrity of COSE envelope
292 publicKeyAlg, err := getSignatureAlgorithm(cert)
293 if err != nil {
294 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
295 }
296 verifier, err := cose.NewVerifier(publicKeyAlg, cert.PublicKey)
297 if err != nil {
298 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
299 }
300 err = e.base.Verify(nil, verifier)
301 if err != nil {
302 return nil, &signature.SignatureIntegrityError{Err: err}
303 }
304
305 // extract content
306 return e.Content()
307 }
308
309 // Content implements signature.Envelope interface.
310 func (e *envelope) Content() (*signature.EnvelopeContent, error) {
311 // sanity check
312 if e.base == nil {
313 return nil, &signature.SignatureEnvelopeNotFoundError{}
314 }
315
316 payload, err := e.payload()
317 if err != nil {
318 return nil, err
319 }
320 signerInfo, err := e.signerInfo()
321 if err != nil {
322 return nil, err
323 }
324 return &signature.EnvelopeContent{
325 SignerInfo: *signerInfo,
326 Payload: *payload,
327 }, nil
328 }
329
330 // Given a COSE envelope, extracts its signature.Payload.
331 func (e *envelope) payload() (*signature.Payload, error) {
332 cty, ok := e.base.Headers.Protected[cose.HeaderLabelContentType]
333 if !ok {
334 return nil, &signature.InvalidSignatureError{Msg: "missing content type"}
335 }
336 var contentType string
337 if contentType, ok = cty.(string); !ok {
338 return nil, &signature.InvalidSignatureError{Msg: "content type should be of 'tstr' type"}
339 }
340 return &signature.Payload{
341 ContentType: contentType,
342 Content: e.base.Payload,
343 }, nil
344 }
345
346 // Given a COSE envelope, extracts its signature.SignerInfo.
347 func (e *envelope) signerInfo() (*signature.SignerInfo, error) {
348 var signerInfo signature.SignerInfo
349
350 // parse signature of COSE envelope, populate signerInfo.Signature
351 sig := e.base.Signature
352 if len(sig) == 0 {
353 return nil, &signature.InvalidSignatureError{Msg: "signature missing in COSE envelope"}
354 }
355 signerInfo.Signature = sig
356
357 // parse protected headers of COSE envelope and populate related
358 // signerInfo fields
359 err := parseProtectedHeaders(e.base.Headers.RawProtected, e.base.Headers.Protected, &signerInfo)
360 if err != nil {
361 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
362 }
363
364 // parse unprotected headers of COSE envelope
365 certs, ok := e.base.Headers.Unprotected[cose.HeaderLabelX5Chain].([]any)
366 if !ok || len(certs) == 0 {
367 return nil, &signature.InvalidSignatureError{Msg: "certificate chain is not present"}
368 }
369 var certChain []*x509.Certificate
370 for _, c := range certs {
371 certRaw, ok := c.([]byte)
372 if !ok {
373 return nil, &signature.InvalidSignatureError{Msg: "certificate chain is not present"}
374 }
375 cert, err := x509.ParseCertificate(certRaw)
376 if err != nil {
377 return nil, &signature.InvalidSignatureError{Msg: err.Error()}
378 }
379 certChain = append(certChain, cert)
380 }
381 // populate signerInfo.CertificateChain
382 signerInfo.CertificateChain = certChain
383
384 // populate signerInfo.UnsignedAttributes.SigningAgent
385 if h, ok := e.base.Headers.Unprotected[headerLabelSigningAgent].(string); ok {
386 signerInfo.UnsignedAttributes.SigningAgent = h
387 }
388
389 // populate signerInfo.UnsignedAttributes.TimestampSignature
390 if timestamepToken, ok := e.base.Headers.Unprotected[headerLabelTimestampSignature].([]byte); ok {
391 signerInfo.UnsignedAttributes.TimestampSignature = timestamepToken
392 }
393
394 return &signerInfo, nil
395 }
396
397 // getSignatureAlgorithm picks up a recommended signing algorithm for given
398 // certificate.
399 func getSignatureAlgorithm(signingCert *x509.Certificate) (cose.Algorithm, error) {
400 keySpec, err := signature.ExtractKeySpec(signingCert)
401 if err != nil {
402 return 0, err
403 }
404 return getSignatureAlgorithmFromKeySpec(keySpec)
405 }
406
407 // getSignatureAlgorithmFromKeySpec ensures the signing algorithm satisfies
408 // algorithm requirements.
409 func getSignatureAlgorithmFromKeySpec(keySpec signature.KeySpec) (cose.Algorithm, error) {
410 switch keySpec.Type {
411 case signature.KeyTypeRSA:
412 switch keySpec.Size {
413 case 2048:
414 return cose.AlgorithmPS256, nil
415 case 3072:
416 return cose.AlgorithmPS384, nil
417 case 4096:
418 return cose.AlgorithmPS512, nil
419 default:
420 return 0, &signature.UnsupportedSigningKeyError{Msg: fmt.Sprintf("RSA: key size %d not supported", keySpec.Size)}
421 }
422 case signature.KeyTypeEC:
423 switch keySpec.Size {
424 case 256:
425 return cose.AlgorithmES256, nil
426 case 384:
427 return cose.AlgorithmES384, nil
428 case 521:
429 return cose.AlgorithmES512, nil
430 default:
431 return 0, &signature.UnsupportedSigningKeyError{Msg: fmt.Sprintf("EC: key size %d not supported", keySpec.Size)}
432 }
433 default:
434 return 0, &signature.UnsupportedSigningKeyError{Msg: "key type not supported"}
435 }
436 }
437
438 // getSigner returns the built-in implementation of cose.Signer from go-cose
439 // or a remote signer implementation of cose.Signer.
440 func getSigner(signer signature.Signer) (signer, error) {
441 if localSigner, ok := signer.(signature.LocalSigner); ok {
442 return newLocalSigner(localSigner)
443 }
444 return newRemoteSigner(signer)
445 }
446
447 // generateProtectedHeaders creates Protected Headers of the COSE envelope
448 // during Sign process.
449 func generateProtectedHeaders(req *signature.SignRequest, protected cose.ProtectedHeader) error {
450 // signingScheme
451 crit := []any{headerLabelSigningScheme}
452 protected[headerLabelSigningScheme] = string(req.SigningScheme)
453
454 // signingTime/authenticSigningTime
455 signingTimeLabel, ok := signingSchemeTimeLabelMap[req.SigningScheme]
456 if !ok {
457 return &signature.InvalidSignRequestError{Msg: "signing scheme: require notary.x509 or notary.x509.signingAuthority"}
458 }
459 rawTimeCBOR, err := encodeTime(req.SigningTime)
460 if err != nil {
461 return &signature.InvalidSignRequestError{Msg: fmt.Sprintf("signing time: %q", err)}
462 }
463 protected[signingTimeLabel] = rawTimeCBOR
464 if signingTimeLabel == headerLabelAuthenticSigningTime {
465 crit = append(crit, headerLabelAuthenticSigningTime)
466 }
467
468 // expiry
469 if !req.Expiry.IsZero() {
470 crit = append(crit, headerLabelExpiry)
471 rawExpiryCBOR, err := encodeTime(req.Expiry)
472 if err != nil {
473 return &signature.InvalidSignRequestError{Msg: fmt.Sprintf("expiry: %q", err)}
474 }
475 protected[headerLabelExpiry] = rawExpiryCBOR
476 }
477
478 // extended attributes
479 for _, elm := range req.ExtendedSignedAttributes {
480 if _, ok := protected[elm.Key]; ok {
481 return &signature.InvalidSignRequestError{Msg: fmt.Sprintf("%q already exists in the protected header", elm.Key)}
482 }
483 if elm.Critical {
484 crit = append(crit, elm.Key)
485 }
486 protected[elm.Key] = elm.Value
487 }
488
489 // critical headers
490 protected[cose.HeaderLabelCritical] = crit
491
492 return nil
493 }
494
495 // generateUnprotectedHeaders creates Unprotected Headers of the COSE envelope
496 // during Sign process.
497 func generateUnprotectedHeaders(req *signature.SignRequest, signer signer, unprotected cose.UnprotectedHeader) {
498 // signing agent
499 if req.SigningAgent != "" {
500 unprotected[headerLabelSigningAgent] = req.SigningAgent
501 }
502
503 // certChain
504 certs := signer.CertificateChain()
505 certChain := make([]any, len(certs))
506 for i, c := range certs {
507 certChain[i] = c.Raw
508 }
509 unprotected[cose.HeaderLabelX5Chain] = certChain
510 }
511
512 // parseProtectedHeaders parses COSE envelope's protected headers and
513 // populates signature.SignerInfo.
514 func parseProtectedHeaders(rawProtected cbor.RawMessage, protected cose.ProtectedHeader, signerInfo *signature.SignerInfo) error {
515 // validate critical headers and return extendedAttributeKeys
516 extendedAttributeKeys, err := validateCritHeaders(protected)
517 if err != nil {
518 return err
519 }
520
521 // populate signerInfo.SignatureAlgorithm
522 alg, err := protected.Algorithm()
523 if err != nil {
524 return err
525 }
526 sigAlg, ok := coseAlgSignatureAlgMap[alg]
527 if !ok {
528 return &signature.InvalidSignatureError{Msg: "signature algorithm not supported: " + strconv.Itoa(int(alg))}
529 }
530 signerInfo.SignatureAlgorithm = sigAlg
531
532 // populate signerInfo.SignedAttributes.SigningScheme
533 // headerLabelSigningScheme header has already been checked by
534 // validateCritHeaders() at the beginning of this function.
535 signingSchemeString := protected[headerLabelSigningScheme].(string)
536 signingScheme := signature.SigningScheme(signingSchemeString)
537 signerInfo.SignedAttributes.SigningScheme = signingScheme
538 signingTimeLabel, ok := signingSchemeTimeLabelMap[signingScheme]
539 if !ok {
540 return &signature.InvalidSignatureError{Msg: "unsupported signingScheme: " + signingSchemeString}
541 }
542
543 // parse CBOR map from raw protected header for tag validation
544 headerMap, err := generateRawProtectedCBORMap(rawProtected)
545 if err != nil {
546 return &signature.InvalidSignatureError{Msg: "generateRawProtectedCBORMap failed: " + err.Error()}
547 }
548
549 // populate signerInfo.SignedAttributes.SigningTime
550 signingTime, err := parseTime(headerMap, signingTimeLabel, protected)
551 if err != nil {
552 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("invalid signingTime: %v", err)}
553 }
554 signerInfo.SignedAttributes.SigningTime = signingTime
555
556 // populate signerInfo.SignedAttributes.Expiry
557 if _, ok := protected[headerLabelExpiry]; ok {
558 expiry, err := parseTime(headerMap, headerLabelExpiry, protected)
559 if err != nil {
560 return &signature.InvalidSignatureError{Msg: fmt.Sprintf("invalid expiry: %v", err)}
561 }
562 signerInfo.SignedAttributes.Expiry = expiry
563 }
564
565 // populate signerInfo.SignedAttributes.ExtendedAttributes
566 signerInfo.SignedAttributes.ExtendedAttributes, err = generateExtendedAttributes(extendedAttributeKeys, protected)
567 return err
568 }
569
570 // validateCritHeaders does a two-way check, namely:
571 // 1. validate that all critical headers are present in the protected bucket
572 // 2. validate that all required headers(as per spec) are marked critical
573 // Returns list of extended attribute keys
574 func validateCritHeaders(protected cose.ProtectedHeader) ([]any, error) {
575 // This ensures all critical headers are present in the protected bucket.
576 labels, err := protected.Critical()
577 if err != nil {
578 return nil, err
579 }
580
581 // set of headers that must be marked as crit
582 mustMarkedCrit := make(map[any]struct{})
583 mustMarkedCrit[headerLabelSigningScheme] = struct{}{}
584 signingScheme, ok := protected[headerLabelSigningScheme].(string)
585 if !ok {
586 return nil, &signature.InvalidSignatureError{Msg: "invalid signingScheme"}
587 }
588 if signature.SigningScheme(signingScheme) == signature.SigningSchemeX509SigningAuthority {
589 mustMarkedCrit[headerLabelAuthenticSigningTime] = struct{}{}
590 }
591 if _, ok := protected[headerLabelExpiry]; ok {
592 mustMarkedCrit[headerLabelExpiry] = struct{}{}
593 }
594
595 // validate that all required headers(as per spec) are marked as critical
596 for _, label := range labels {
597 delete(mustMarkedCrit, label)
598 }
599 if len(mustMarkedCrit) != 0 {
600 headers := make([]any, 0, len(mustMarkedCrit))
601 for k := range mustMarkedCrit {
602 headers = append(headers, k)
603 }
604 return nil, &signature.InvalidSignatureError{Msg: fmt.Sprintf("these required headers are not marked as critical: %v", headers)}
605 }
606
607 // fetch all the extended signed attributes
608 systemHeaders := []any{cose.HeaderLabelAlgorithm, cose.HeaderLabelCritical, cose.HeaderLabelContentType,
609 headerLabelExpiry, headerLabelSigningScheme, headerLabelSigningTime, headerLabelAuthenticSigningTime}
610 var extendedAttributeKeys []any
611 for label := range protected {
612 if contains(systemHeaders, label) {
613 continue
614 }
615 extendedAttributeKeys = append(extendedAttributeKeys, label)
616 }
617
618 return extendedAttributeKeys, nil
619 }
620
621 // generateExtendedAttributes generates []signature.Attribute during
622 // SignerInfo process.
623 func generateExtendedAttributes(extendedAttributeKeys []any, protected cose.ProtectedHeader) ([]signature.Attribute, error) {
624 criticalHeaders, ok := protected[cose.HeaderLabelCritical].([]any)
625 if !ok {
626 return nil, &signature.InvalidSignatureError{Msg: "invalid critical headers"}
627 }
628 var extendedAttr []signature.Attribute
629 for _, key := range extendedAttributeKeys {
630 extendedAttr = append(extendedAttr, signature.Attribute{
631 Key: key,
632 Critical: contains(criticalHeaders, key),
633 Value: protected[key],
634 })
635 }
636 return extendedAttr, nil
637 }
638
639 // contains checks if e is in s
640 func contains(s []any, e any) bool {
641 for _, a := range s {
642 if a == e {
643 return true
644 }
645 }
646 return false
647 }
648
649 // encodeTime generates a Tag1 Datetime CBOR object and casts it to
650 // cbor.RawMessage
651 func encodeTime(t time.Time) (cbor.RawMessage, error) {
652 timeCBOR, err := encMode.Marshal(t)
653 if err != nil {
654 return nil, err
655 }
656
657 return cbor.RawMessage(timeCBOR), nil
658 }
659
660 // decodeTime decodes cbor.RawMessage of Tag1 Datetime CBOR object
661 // into time.Time
662 //
663 // For more details: https://github.com/fxamacker/cbor/blob/7704fa5efaf3ef4ac35aff38f50f6ff567793072/decode.go#L52
664 func decodeTime(timeRaw cbor.RawMessage) (time.Time, error) {
665 var t time.Time
666 err := decMode.Unmarshal([]byte(timeRaw), &t)
667 if err != nil {
668 return time.Time{}, err
669 }
670
671 return t, nil
672 }
673
674 // parseTime validates Tag1 Datetime in headerMap given label, then returns
675 // time.Time value from cose.ProtectedHeader.
676 func parseTime(headerMap map[any]cbor.RawMessage, label string, protected cose.ProtectedHeader) (time.Time, error) {
677 switch t := protected[label].(type) {
678 // cbor.RawMessage indicates the signing process.
679 case cbor.RawMessage:
680 return decodeTime(t)
681 // time.Time indicates the verififcation process.
682 // only need to validate Tag1 Datetime during verification.
683 case time.Time:
684 rawMsg, ok := headerMap[label]
685 if !ok {
686 return time.Time{}, fmt.Errorf("headerMap is missing label %q", label)
687 }
688 rawTag := &cbor.RawTag{}
689 err := rawTag.UnmarshalCBOR([]byte(rawMsg))
690 if err != nil {
691 return time.Time{}, fmt.Errorf("header %q time value does not have a tag", label)
692 }
693 if rawTag.Number != 1 {
694 return time.Time{}, errors.New("only Tag `1` Datetime CBOR object is supported")
695 }
696 return t, nil
697 case nil:
698 return time.Time{}, fmt.Errorf("protected header %q is missing", label)
699 }
700
701 return time.Time{}, errors.New("invalid timeValue type")
702 }
703
704 // generateRawProtectedCBORMap unmarshals rawProtected Header of COSE
705 // envelope into a headerMap.
706 func generateRawProtectedCBORMap(rawProtected cbor.RawMessage) (map[any]cbor.RawMessage, error) {
707 // empty rawProtected indicates signing process
708 if len(rawProtected) == 0 {
709 return nil, nil
710 }
711
712 var decoded []byte
713 err := decMode.Unmarshal(rawProtected, &decoded)
714 if err != nil {
715 return nil, err
716 }
717 var headerMap map[any]cbor.RawMessage
718 err = cbor.Unmarshal(decoded, &headerMap)
719 if err != nil {
720 return nil, err
721 }
722
723 return headerMap, nil
724 }
725
726 // hashFromCOSEAlgorithm maps the cose algorithm supported by go-cose to hash
727 func hashFromCOSEAlgorithm(alg cose.Algorithm) (crypto.Hash, error) {
728 switch alg {
729 case cose.AlgorithmPS256, cose.AlgorithmES256:
730 return crypto.SHA256, nil
731 case cose.AlgorithmPS384, cose.AlgorithmES384:
732 return crypto.SHA384, nil
733 case cose.AlgorithmPS512, cose.AlgorithmES512:
734 return crypto.SHA512, nil
735 default:
736 return 0, fmt.Errorf("unsupported cose algorithm %s", alg)
737 }
738 }