Debian Codegraph @

ietf-cms/protocol/protocol.go

raw symbols SCIP
1 // Package protocol implements low level CMS types, parsing and generation.
2 package protocol
3
4 import (
5 "bytes"
6 "crypto"
7 "crypto/ecdsa"
8 "crypto/elliptic"
9 "crypto/rand"
10 _ "crypto/sha1" // for crypto.SHA1
11 "crypto/x509"
12 "crypto/x509/pkix"
13 "encoding/asn1"
14 "errors"
15 "fmt"
16 "math/big"
17 "sort"
18 "time"
19
20 "github.com/github/smimesign/ietf-cms/oid"
21 )
22
23 // ASN1Error is an error from parsing ASN.1 structures.
24 type ASN1Error struct {
25 Message string
26 }
27
28 // Error implements the error interface.
29 func (err ASN1Error) Error() string {
30 return fmt.Sprintf("cms/protocol: ASN.1 Error — %s", err.Message)
31 }
32
33 var (
34 // ErrWrongType is returned by methods that make assumptions about types.
35 // Helper methods are defined for accessing CHOICE and ANY feilds. These
36 // helper methods get the value of the field, assuming it is of a given type.
37 // This error is returned if that assumption is wrong and the field has a
38 // different type.
39 ErrWrongType = errors.New("cms/protocol: wrong choice or any type")
40
41 // ErrNoCertificate is returned when a requested certificate cannot be found.
42 ErrNoCertificate = errors.New("no certificate found")
43
44 // ErrUnsupported is returned when an unsupported type or version
45 // is encountered.
46 ErrUnsupported = ASN1Error{"unsupported type or version"}
47
48 // ErrTrailingData is returned when extra data is found after parsing an ASN.1
49 // structure.
50 ErrTrailingData = ASN1Error{"unexpected trailing data"}
51 )
52
53 // ContentInfo ::= SEQUENCE {
54 // contentType ContentType,
55 // content [0] EXPLICIT ANY DEFINED BY contentType }
56 //
57 // ContentType ::= OBJECT IDENTIFIER
58 type ContentInfo struct {
59 ContentType asn1.ObjectIdentifier
60 Content asn1.RawValue `asn1:"explicit,tag:0"`
61 }
62
63 // ParseContentInfo parses a top-level ContentInfo type from BER encoded data.
64 func ParseContentInfo(ber []byte) (ci ContentInfo, err error) {
65 var der []byte
66 if der, err = BER2DER(ber); err != nil {
67 return
68 }
69
70 var rest []byte
71 if rest, err = asn1.Unmarshal(der, &ci); err != nil {
72 return
73 }
74 if len(rest) > 0 {
75 err = ErrTrailingData
76 }
77
78 return
79 }
80
81 // SignedDataContent gets the content assuming contentType is signedData.
82 func (ci ContentInfo) SignedDataContent() (*SignedData, error) {
83 if !ci.ContentType.Equal(oid.ContentTypeSignedData) {
84 return nil, ErrWrongType
85 }
86
87 sd := new(SignedData)
88 if rest, err := asn1.Unmarshal(ci.Content.Bytes, sd); err != nil {
89 return nil, err
90 } else if len(rest) > 0 {
91 return nil, ErrTrailingData
92 }
93
94 return sd, nil
95 }
96
97 // EncapsulatedContentInfo ::= SEQUENCE {
98 // eContentType ContentType,
99 // eContent [0] EXPLICIT OCTET STRING OPTIONAL }
100 //
101 // ContentType ::= OBJECT IDENTIFIER
102 type EncapsulatedContentInfo struct {
103 EContentType asn1.ObjectIdentifier
104 EContent asn1.RawValue `asn1:"optional,explicit,tag:0"`
105 }
106
107 // NewDataEncapsulatedContentInfo creates a new EncapsulatedContentInfo of type
108 // id-data.
109 func NewDataEncapsulatedContentInfo(data []byte) (EncapsulatedContentInfo, error) {
110 return NewEncapsulatedContentInfo(oid.ContentTypeData, data)
111 }
112
113 // NewEncapsulatedContentInfo creates a new EncapsulatedContentInfo.
114 func NewEncapsulatedContentInfo(contentType asn1.ObjectIdentifier, content []byte) (EncapsulatedContentInfo, error) {
115 octets, err := asn1.Marshal(asn1.RawValue{
116 Class: asn1.ClassUniversal,
117 Tag: asn1.TagOctetString,
118 Bytes: content,
119 IsCompound: false,
120 })
121 if err != nil {
122 return EncapsulatedContentInfo{}, err
123 }
124
125 return EncapsulatedContentInfo{
126 EContentType: contentType,
127 EContent: asn1.RawValue{
128 Class: asn1.ClassContextSpecific,
129 Tag: 0,
130 Bytes: octets,
131 IsCompound: true,
132 },
133 }, nil
134 }
135
136 // EContentValue gets the OCTET STRING EContent value without tag or length.
137 // This is what the message digest is calculated over. A nil byte slice is
138 // returned if the OPTIONAL eContent field is missing.
139 func (eci EncapsulatedContentInfo) EContentValue() ([]byte, error) {
140 if eci.EContent.Bytes == nil {
141 return nil, nil
142 }
143
144 // The EContent is an `[0] EXPLICIT OCTET STRING`. EXPLICIT means that there
145 // is another whole tag wrapping the OCTET STRING. When we decoded the
146 // EContent into a asn1.RawValue we're just getting that outer tag, so the
147 // EContent.Bytes is the encoded OCTET STRING, which is what we really want
148 // the value of.
149 var octets asn1.RawValue
150 if rest, err := asn1.Unmarshal(eci.EContent.Bytes, &octets); err != nil {
151 return nil, err
152 } else if len(rest) > 0 {
153 return nil, ErrTrailingData
154 }
155 if octets.Class != asn1.ClassUniversal || octets.Tag != asn1.TagOctetString {
156 return nil, ASN1Error{"bad tag or class"}
157 }
158
159 // While we already tried converting BER to DER, we didn't take constructed
160 // types into account. Constructed string types, as opposed to primitive
161 // types, can encode indefinite length strings by including a bunch of
162 // sub-strings that are joined together to get the actual value. Gpgsm uses
163 // a constructed OCTET STRING for the EContent, so we have to manually decode
164 // it here.
165 var value []byte
166 if octets.IsCompound {
167 rest := octets.Bytes
168 for len(rest) > 0 {
169 var err error
170 if rest, err = asn1.Unmarshal(rest, &octets); err != nil {
171 return nil, err
172 }
173
174 // Don't allow further constructed types.
175 if octets.Class != asn1.ClassUniversal || octets.Tag != asn1.TagOctetString || octets.IsCompound {
176 return nil, ASN1Error{"bad class or tag"}
177 }
178
179 value = append(value, octets.Bytes...)
180 }
181 } else {
182 value = octets.Bytes
183 }
184
185 return value, nil
186 }
187
188 // IsTypeData checks if the EContentType is id-data.
189 func (eci EncapsulatedContentInfo) IsTypeData() bool {
190 return eci.EContentType.Equal(oid.ContentTypeData)
191 }
192
193 // DataEContent gets the EContent assuming EContentType is data.
194 func (eci EncapsulatedContentInfo) DataEContent() ([]byte, error) {
195 if !eci.IsTypeData() {
196 return nil, ErrWrongType
197 }
198 return eci.EContentValue()
199 }
200
201 // Attribute ::= SEQUENCE {
202 // attrType OBJECT IDENTIFIER,
203 // attrValues SET OF AttributeValue }
204 //
205 // AttributeValue ::= ANY
206 type Attribute struct {
207 Type asn1.ObjectIdentifier
208
209 // This should be a SET OF ANY, but Go's asn1 parser can't handle slices of
210 // RawValues. Use value() to get an AnySet of the value.
211 RawValue asn1.RawValue
212 }
213
214 // NewAttribute creates a single-value Attribute.
215 func NewAttribute(typ asn1.ObjectIdentifier, val interface{}) (attr Attribute, err error) {
216 var der []byte
217 if der, err = asn1.Marshal(val); err != nil {
218 return
219 }
220
221 var rv asn1.RawValue
222 if _, err = asn1.Unmarshal(der, &rv); err != nil {
223 return
224 }
225
226 if err = NewAnySet(rv).Encode(&attr.RawValue); err != nil {
227 return
228 }
229
230 attr.Type = typ
231
232 return
233 }
234
235 // Value further decodes the attribute Value as a SET OF ANY, which Go's asn1
236 // parser can't handle directly.
237 func (a Attribute) Value() (AnySet, error) {
238 return DecodeAnySet(a.RawValue)
239 }
240
241 // Attributes is a common Go type for SignedAttributes and UnsignedAttributes.
242 //
243 // SignedAttributes ::= SET SIZE (1..MAX) OF Attribute
244 //
245 // UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute
246 type Attributes []Attribute
247
248 // MarshaledForSigning DER encodes the Attributes as needed for signing
249 // SignedAttributes. RFC5652 explains this encoding:
250 // A separate encoding of the signedAttrs field is performed for message
251 // digest calculation. The IMPLICIT [0] tag in the signedAttrs is not used for
252 // the DER encoding, rather an EXPLICIT SET OF tag is used. That is, the DER
253 // encoding of the EXPLICIT SET OF tag, rather than of the IMPLICIT [0] tag,
254 // MUST be included in the message digest calculation along with the length
255 // and content octets of the SignedAttributes value.
256 func (attrs Attributes) MarshaledForSigning() ([]byte, error) {
257 seq, err := asn1.Marshal(struct {
258 Attributes `asn1:"set"`
259 }{attrs})
260
261 if err != nil {
262 return nil, err
263 }
264
265 // unwrap the outer SEQUENCE
266 var raw asn1.RawValue
267 if _, err = asn1.Unmarshal(seq, &raw); err != nil {
268 return nil, err
269 }
270
271 return raw.Bytes, nil
272 }
273
274 // MarshaledForVerification DER encodes the Attributes as needed for
275 // verification of SignedAttributes. This is done differently than
276 // MarshaledForSigning because when verifying attributes, we need to
277 // use the received order.
278 func (attrs Attributes) MarshaledForVerification() ([]byte, error) {
279 seq, err := asn1.Marshal(struct {
280 Attributes `asn1:"sequence"`
281 }{attrs})
282
283 if err != nil {
284 return nil, err
285 }
286
287 // unwrap the outer SEQUENCE
288 var raw asn1.RawValue
289 if _, err = asn1.Unmarshal(seq, &raw); err != nil {
290 return nil, err
291 }
292
293 // Change SEQUENCE OF to SET OF.
294 raw.Bytes[0] = 0x31
295 return raw.Bytes, nil
296 }
297
298 // GetOnlyAttributeValueBytes gets an attribute value, returning an error if the
299 // attribute occurs multiple times or has multiple values.
300 func (attrs Attributes) GetOnlyAttributeValueBytes(oid asn1.ObjectIdentifier) (rv asn1.RawValue, err error) {
301 var vals []AnySet
302 if vals, err = attrs.GetValues(oid); err != nil {
303 return
304 }
305 if len(vals) != 1 {
306 err = ASN1Error{"bad attribute count"}
307 return
308 }
309 if len(vals[0].Elements) != 1 {
310 err = ASN1Error{"bad attribute element count"}
311 return
312 }
313
314 return vals[0].Elements[0], nil
315 }
316
317 // GetValues retreives the attributes with the given OID. A nil value is
318 // returned if the OPTIONAL SET of Attributes is missing from the SignerInfo. An
319 // empty slice is returned if the specified attribute isn't in the set.
320 func (attrs Attributes) GetValues(oid asn1.ObjectIdentifier) ([]AnySet, error) {
321 if attrs == nil {
322 return nil, nil
323 }
324
325 vals := []AnySet{}
326 for _, attr := range attrs {
327 if attr.Type.Equal(oid) {
328 val, err := attr.Value()
329 if err != nil {
330 return nil, err
331 }
332
333 vals = append(vals, val)
334 }
335 }
336
337 return vals, nil
338 }
339
340 // HasAttribute checks if an attribute is present.
341 func (attrs Attributes) HasAttribute(oid asn1.ObjectIdentifier) bool {
342 for _, attr := range attrs {
343 if attr.Type.Equal(oid) {
344 return true
345 }
346 }
347
348 return false
349 }
350
351 // IssuerAndSerialNumber ::= SEQUENCE {
352 // issuer Name,
353 // serialNumber CertificateSerialNumber }
354 //
355 // CertificateSerialNumber ::= INTEGER
356 type IssuerAndSerialNumber struct {
357 Issuer asn1.RawValue
358 SerialNumber *big.Int
359 }
360
361 // NewIssuerAndSerialNumber creates a IssuerAndSerialNumber SID for the given
362 // cert.
363 func NewIssuerAndSerialNumber(cert *x509.Certificate) (rv asn1.RawValue, err error) {
364 sid := IssuerAndSerialNumber{
365 SerialNumber: new(big.Int).Set(cert.SerialNumber),
366 }
367
368 if _, err = asn1.Unmarshal(cert.RawIssuer, &sid.Issuer); err != nil {
369 return
370 }
371
372 var der []byte
373 if der, err = asn1.Marshal(sid); err != nil {
374 return
375 }
376
377 if _, err = asn1.Unmarshal(der, &rv); err != nil {
378 return
379 }
380
381 return
382 }
383
384 // SignerInfo ::= SEQUENCE {
385 // version CMSVersion,
386 // sid SignerIdentifier,
387 // digestAlgorithm DigestAlgorithmIdentifier,
388 // signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
389 // signatureAlgorithm SignatureAlgorithmIdentifier,
390 // signature SignatureValue,
391 // unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }
392 //
393 // CMSVersion ::= INTEGER
394 // { v0(0), v1(1), v2(2), v3(3), v4(4), v5(5) }
395 //
396 // SignerIdentifier ::= CHOICE {
397 // issuerAndSerialNumber IssuerAndSerialNumber,
398 // subjectKeyIdentifier [0] SubjectKeyIdentifier }
399 //
400 // DigestAlgorithmIdentifier ::= AlgorithmIdentifier
401 //
402 // SignedAttributes ::= SET SIZE (1..MAX) OF Attribute
403 //
404 // SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
405 //
406 // SignatureValue ::= OCTET STRING
407 //
408 // UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute
409 type SignerInfo struct {
410 Version int
411 SID asn1.RawValue
412 DigestAlgorithm pkix.AlgorithmIdentifier
413 SignedAttrs Attributes `asn1:"optional,tag:0"`
414 SignatureAlgorithm pkix.AlgorithmIdentifier
415 Signature []byte
416 UnsignedAttrs Attributes `asn1:"set,optional,tag:1"`
417 }
418
419 // FindCertificate finds this SignerInfo's certificate in a slice of
420 // certificates.
421 func (si SignerInfo) FindCertificate(certs []*x509.Certificate) (*x509.Certificate, error) {
422 switch si.Version {
423 case 1: // SID is issuer and serial number
424 isn, err := si.issuerAndSerialNumberSID()
425 if err != nil {
426 return nil, err
427 }
428
429 for _, cert := range certs {
430 if bytes.Equal(cert.RawIssuer, isn.Issuer.FullBytes) && isn.SerialNumber.Cmp(cert.SerialNumber) == 0 {
431 return cert, nil
432 }
433 }
434 case 3: // SID is SubjectKeyIdentifier
435 ski, err := si.subjectKeyIdentifierSID()
436 if err != nil {
437 return nil, err
438 }
439
440 for _, cert := range certs {
441 for _, ext := range cert.Extensions {
442 if oid.ExtensionSubjectKeyIdentifier.Equal(ext.Id) {
443 if bytes.Equal(ski, ext.Value) {
444 return cert, nil
445 }
446 }
447 }
448 }
449 default:
450 return nil, ErrUnsupported
451 }
452
453 return nil, ErrNoCertificate
454 }
455
456 // issuerAndSerialNumberSID gets the SID, assuming it is a issuerAndSerialNumber.
457 func (si SignerInfo) issuerAndSerialNumberSID() (isn IssuerAndSerialNumber, err error) {
458 if si.SID.Class != asn1.ClassUniversal || si.SID.Tag != asn1.TagSequence {
459 err = ErrWrongType
460 return
461 }
462
463 var rest []byte
464 if rest, err = asn1.Unmarshal(si.SID.FullBytes, &isn); err == nil && len(rest) > 0 {
465 err = ErrTrailingData
466 }
467
468 return
469 }
470
471 // subjectKeyIdentifierSID gets the SID, assuming it is a subjectKeyIdentifier.
472 func (si SignerInfo) subjectKeyIdentifierSID() ([]byte, error) {
473 if si.SID.Class != asn1.ClassContextSpecific || si.SID.Tag != 0 {
474 return nil, ErrWrongType
475 }
476
477 return si.SID.Bytes, nil
478 }
479
480 // Hash gets the crypto.Hash associated with this SignerInfo's DigestAlgorithm.
481 // 0 is returned for unrecognized algorithms.
482 func (si SignerInfo) Hash() (crypto.Hash, error) {
483 algo := si.DigestAlgorithm.Algorithm.String()
484 hash := oid.DigestAlgorithmToCryptoHash[algo]
485 if hash == 0 || !hash.Available() {
486 return 0, ErrUnsupported
487 }
488
489 return hash, nil
490 }
491
492 // X509SignatureAlgorithm gets the x509.SignatureAlgorithm that should be used
493 // for verifying this SignerInfo's signature.
494 func (si SignerInfo) X509SignatureAlgorithm() x509.SignatureAlgorithm {
495 var (
496 sigOID = si.SignatureAlgorithm.Algorithm.String()
497 digestOID = si.DigestAlgorithm.Algorithm.String()
498 )
499
500 if sa := oid.SignatureAlgorithmToX509SignatureAlgorithm[sigOID]; sa != x509.UnknownSignatureAlgorithm {
501 return sa
502 }
503
504 return oid.PublicKeyAndDigestAlgorithmToX509SignatureAlgorithm[sigOID][digestOID]
505 }
506
507 // GetContentTypeAttribute gets the signed ContentType attribute from the
508 // SignerInfo.
509 func (si SignerInfo) GetContentTypeAttribute() (asn1.ObjectIdentifier, error) {
510 rv, err := si.SignedAttrs.GetOnlyAttributeValueBytes(oid.AttributeContentType)
511 if err != nil {
512 return nil, err
513 }
514
515 var ct asn1.ObjectIdentifier
516 if rest, err := asn1.Unmarshal(rv.FullBytes, &ct); err != nil {
517 return nil, err
518 } else if len(rest) > 0 {
519 return nil, ErrTrailingData
520 }
521
522 return ct, nil
523 }
524
525 // GetMessageDigestAttribute gets the signed MessageDigest attribute from the
526 // SignerInfo.
527 func (si SignerInfo) GetMessageDigestAttribute() ([]byte, error) {
528 rv, err := si.SignedAttrs.GetOnlyAttributeValueBytes(oid.AttributeMessageDigest)
529 if err != nil {
530 return nil, err
531 }
532 if rv.Class != asn1.ClassUniversal || rv.Tag != asn1.TagOctetString {
533 return nil, ASN1Error{"bad class or tag"}
534 }
535
536 return rv.Bytes, nil
537 }
538
539 // GetSigningTimeAttribute gets the signed SigningTime attribute from the
540 // SignerInfo.
541 func (si SignerInfo) GetSigningTimeAttribute() (time.Time, error) {
542 var t time.Time
543
544 if !si.SignedAttrs.HasAttribute(oid.AttributeSigningTime) {
545 return t, nil
546 }
547 rv, err := si.SignedAttrs.GetOnlyAttributeValueBytes(oid.AttributeSigningTime)
548 if err != nil {
549 return t, err
550 }
551 if rv.Class != asn1.ClassUniversal || (rv.Tag != asn1.TagUTCTime && rv.Tag != asn1.TagGeneralizedTime) {
552 return t, ASN1Error{"bad class or tag"}
553 }
554
555 if rest, err := asn1.Unmarshal(rv.FullBytes, &t); err != nil {
556 return t, err
557 } else if len(rest) > 0 {
558 return t, ErrTrailingData
559 }
560
561 return t, nil
562 }
563
564 // SignedData ::= SEQUENCE {
565 // version CMSVersion,
566 // digestAlgorithms DigestAlgorithmIdentifiers,
567 // encapContentInfo EncapsulatedContentInfo,
568 // certificates [0] IMPLICIT CertificateSet OPTIONAL,
569 // crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
570 // signerInfos SignerInfos }
571 //
572 // CMSVersion ::= INTEGER
573 // { v0(0), v1(1), v2(2), v3(3), v4(4), v5(5) }
574 //
575 // DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
576 //
577 // CertificateSet ::= SET OF CertificateChoices
578 //
579 // CertificateChoices ::= CHOICE {
580 // certificate Certificate,
581 // extendedCertificate [0] IMPLICIT ExtendedCertificate, -- Obsolete
582 // v1AttrCert [1] IMPLICIT AttributeCertificateV1, -- Obsolete
583 // v2AttrCert [2] IMPLICIT AttributeCertificateV2,
584 // other [3] IMPLICIT OtherCertificateFormat }
585 //
586 // OtherCertificateFormat ::= SEQUENCE {
587 // otherCertFormat OBJECT IDENTIFIER,
588 // otherCert ANY DEFINED BY otherCertFormat }
589 //
590 // RevocationInfoChoices ::= SET OF RevocationInfoChoice
591 //
592 // RevocationInfoChoice ::= CHOICE {
593 // crl CertificateList,
594 // other [1] IMPLICIT OtherRevocationInfoFormat }
595 //
596 // OtherRevocationInfoFormat ::= SEQUENCE {
597 // otherRevInfoFormat OBJECT IDENTIFIER,
598 // otherRevInfo ANY DEFINED BY otherRevInfoFormat }
599 //
600 // SignerInfos ::= SET OF SignerInfo
601 type SignedData struct {
602 Version int
603 DigestAlgorithms []pkix.AlgorithmIdentifier `asn1:"set"`
604 EncapContentInfo EncapsulatedContentInfo
605 Certificates []asn1.RawValue `asn1:"optional,set,tag:0"`
606 CRLs []asn1.RawValue `asn1:"optional,set,tag:1"`
607 SignerInfos []SignerInfo `asn1:"set"`
608 }
609
610 // NewSignedData creates a new SignedData.
611 func NewSignedData(eci EncapsulatedContentInfo) (*SignedData, error) {
612 // The version is picked based on which CMS features are used. We only use
613 // version 1 features, except for supporting non-data econtent.
614 version := 1
615 if !eci.IsTypeData() {
616 version = 3
617 }
618
619 return &SignedData{
620 Version: version,
621 DigestAlgorithms: []pkix.AlgorithmIdentifier{},
622 EncapContentInfo: eci,
623 SignerInfos: []SignerInfo{},
624 }, nil
625 }
626
627 // AddSignerInfo adds a SignerInfo to the SignedData.
628 func (sd *SignedData) AddSignerInfo(chain []*x509.Certificate, signer crypto.Signer) error {
629 // figure out which certificate is associated with signer.
630 pub, err := x509.MarshalPKIXPublicKey(signer.Public())
631 if err != nil {
632 return err
633 }
634
635 var (
636 cert *x509.Certificate
637 certPub []byte
638 )
639
640 for _, c := range chain {
641 if err = sd.AddCertificate(c); err != nil {
642 return err
643 }
644
645 if certPub, err = x509.MarshalPKIXPublicKey(c.PublicKey); err != nil {
646 return err
647 }
648
649 if bytes.Equal(pub, certPub) {
650 cert = c
651 }
652 }
653 if cert == nil {
654 return ErrNoCertificate
655 }
656
657 sid, err := NewIssuerAndSerialNumber(cert)
658 if err != nil {
659 return err
660 }
661
662 digestAlgorithmID := digestAlgorithmForPublicKey(pub)
663
664 signatureAlgorithmOID, ok := oid.X509PublicKeyAndDigestAlgorithmToSignatureAlgorithm[cert.PublicKeyAlgorithm][digestAlgorithmID.Algorithm.String()]
665 if !ok {
666 return errors.New("unsupported certificate public key algorithm")
667 }
668
669 signatureAlgorithmID := pkix.AlgorithmIdentifier{Algorithm: signatureAlgorithmOID}
670
671 si := SignerInfo{
672 Version: 1,
673 SID: sid,
674 DigestAlgorithm: digestAlgorithmID,
675 SignedAttrs: nil,
676 SignatureAlgorithm: signatureAlgorithmID,
677 Signature: nil,
678 UnsignedAttrs: nil,
679 }
680
681 // Get the message
682 content, err := sd.EncapContentInfo.EContentValue()
683 if err != nil {
684 return err
685 }
686 if content == nil {
687 return errors.New("already detached")
688 }
689
690 // Digest the message.
691 hash, err := si.Hash()
692 if err != nil {
693 return err
694 }
695 md := hash.New()
696 if _, err = md.Write(content); err != nil {
697 return err
698 }
699
700 // Build our SignedAttributes
701 stAttr, err := NewAttribute(oid.AttributeSigningTime, time.Now().UTC())
702 if err != nil {
703 return err
704 }
705 mdAttr, err := NewAttribute(oid.AttributeMessageDigest, md.Sum(nil))
706 if err != nil {
707 return err
708 }
709 ctAttr, err := NewAttribute(oid.AttributeContentType, sd.EncapContentInfo.EContentType)
710 if err != nil {
711 return err
712 }
713
714 // sort attributes to match required order in marshaled form
715 si.SignedAttrs, err = sortAttributes(stAttr, mdAttr, ctAttr)
716 if err != nil {
717 return err
718 }
719
720 // Signature is over the marshaled signed attributes
721 sm, err := si.SignedAttrs.MarshaledForSigning()
722 if err != nil {
723 return err
724 }
725 smd := hash.New()
726 if _, errr := smd.Write(sm); errr != nil {
727 return errr
728 }
729 if si.Signature, err = signer.Sign(rand.Reader, smd.Sum(nil), hash); err != nil {
730 return err
731 }
732
733 sd.addDigestAlgorithm(si.DigestAlgorithm)
734
735 sd.SignerInfos = append(sd.SignerInfos, si)
736
737 return nil
738 }
739
740 func sortAttributes(attrs ...Attribute) ([]Attribute, error) {
741 // Sort attrs by their encoded values (including tag and
742 // lengths) as specified in X690 Section 11.6 and implemented
743 // in go >= 1.15's asn1.Marshal().
744 sort.Slice(attrs, func(i, j int) bool {
745 return bytes.Compare(
746 attrs[i].RawValue.FullBytes,
747 attrs[j].RawValue.FullBytes) < 0
748 })
749
750 return attrs, nil
751 }
752
753 // algorithmsForPublicKey takes an opinionated stance on what algorithms to use
754 // for the given public key.
755 func digestAlgorithmForPublicKey(pub crypto.PublicKey) pkix.AlgorithmIdentifier {
756 if ecPub, ok := pub.(*ecdsa.PublicKey); ok {
757 switch ecPub.Curve {
758 case elliptic.P384():
759 return pkix.AlgorithmIdentifier{Algorithm: oid.DigestAlgorithmSHA384}
760 case elliptic.P521():
761 return pkix.AlgorithmIdentifier{Algorithm: oid.DigestAlgorithmSHA512}
762 }
763 }
764
765 return pkix.AlgorithmIdentifier{Algorithm: oid.DigestAlgorithmSHA256}
766 }
767
768 // ClearCertificates removes all certificates.
769 func (sd *SignedData) ClearCertificates() {
770 sd.Certificates = []asn1.RawValue{}
771 }
772
773 // AddCertificate adds a *x509.Certificate.
774 func (sd *SignedData) AddCertificate(cert *x509.Certificate) error {
775 for _, existing := range sd.Certificates {
776 if bytes.Equal(existing.Bytes, cert.Raw) {
777 return errors.New("certificate already added")
778 }
779 }
780
781 var rv asn1.RawValue
782 if _, err := asn1.Unmarshal(cert.Raw, &rv); err != nil {
783 return err
784 }
785
786 sd.Certificates = append(sd.Certificates, rv)
787
788 return nil
789 }
790
791 // addDigestAlgorithm adds a new AlgorithmIdentifier if it doesn't exist yet.
792 func (sd *SignedData) addDigestAlgorithm(algo pkix.AlgorithmIdentifier) {
793 for _, existing := range sd.DigestAlgorithms {
794 if existing.Algorithm.Equal(algo.Algorithm) {
795 return
796 }
797 }
798
799 sd.DigestAlgorithms = append(sd.DigestAlgorithms, algo)
800 }
801
802 // X509Certificates gets the certificates, assuming that they're X.509 encoded.
803 func (sd *SignedData) X509Certificates() ([]*x509.Certificate, error) {
804 // Certificates field is optional. Handle missing value.
805 if sd.Certificates == nil {
806 return nil, nil
807 }
808
809 // Empty set
810 if len(sd.Certificates) == 0 {
811 return []*x509.Certificate{}, nil
812 }
813
814 certs := make([]*x509.Certificate, 0, len(sd.Certificates))
815 for _, raw := range sd.Certificates {
816 if raw.Class != asn1.ClassUniversal || raw.Tag != asn1.TagSequence {
817 return nil, ErrUnsupported
818 }
819
820 x509, err := x509.ParseCertificate(raw.FullBytes)
821 if err != nil {
822 return nil, err
823 }
824
825 certs = append(certs, x509)
826 }
827
828 return certs, nil
829 }
830
831 // ContentInfo returns the SignedData wrapped in a ContentInfo packet.
832 func (sd *SignedData) ContentInfo() (ContentInfo, error) {
833 var nilCI ContentInfo
834
835 der, err := asn1.Marshal(*sd)
836 if err != nil {
837 return nilCI, err
838 }
839
840 return ContentInfo{
841 ContentType: oid.ContentTypeSignedData,
842 Content: asn1.RawValue{
843 Class: asn1.ClassContextSpecific,
844 Tag: 0,
845 Bytes: der,
846 IsCompound: true,
847 },
848 }, nil
849
850 }
851
852 // ContentInfoDER returns the SignedData wrapped in a ContentInfo packet and DER
853 // encoded.
854 func (sd *SignedData) ContentInfoDER() ([]byte, error) {
855 ci, err := sd.ContentInfo()
856 if err != nil {
857 return nil, err
858 }
859
860 return asn1.Marshal(ci)
861 }