Debian Codegraph @

sign.go

raw symbols SCIP
1 package pkcs7
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/dsa"
7 "crypto/rand"
8 "crypto/x509"
9 "crypto/x509/pkix"
10 "encoding/asn1"
11 "errors"
12 "fmt"
13 "math/big"
14 "sync"
15 "time"
16 )
17
18 func init() {
19 defaultMessageDigestAlgorithm.oid = OIDDigestAlgorithmSHA1
20 }
21
22 var defaultMessageDigestAlgorithm struct {
23 sync.RWMutex
24 oid asn1.ObjectIdentifier
25 }
26
27 // SetDefaultDigestAlgorithm sets the default digest algorithm
28 // to be used for signing operations on [SignedData].
29 //
30 // This must be called before creating a new instance of [SignedData]
31 // using [NewSignedData].
32 //
33 // When this function is not called, the default digest algorithm is SHA1.
34 func SetDefaultDigestAlgorithm(d asn1.ObjectIdentifier) error {
35 defaultMessageDigestAlgorithm.Lock()
36 defer defaultMessageDigestAlgorithm.Unlock()
37
38 switch {
39 case d.Equal(OIDDigestAlgorithmSHA1),
40 d.Equal(OIDDigestAlgorithmSHA224), d.Equal(OIDDigestAlgorithmSHA256),
41 d.Equal(OIDDigestAlgorithmSHA384), d.Equal(OIDDigestAlgorithmSHA512),
42 d.Equal(OIDDigestAlgorithmDSA), d.Equal(OIDDigestAlgorithmDSASHA1),
43 d.Equal(OIDDigestAlgorithmECDSASHA1), d.Equal(OIDDigestAlgorithmECDSASHA256),
44 d.Equal(OIDDigestAlgorithmECDSASHA384), d.Equal(OIDDigestAlgorithmECDSASHA512):
45 break
46 default:
47 return fmt.Errorf("unsupported message digest algorithm %v", d)
48 }
49
50 defaultMessageDigestAlgorithm.oid = d
51
52 return nil
53 }
54
55 func defaultMessageDigestAlgorithmOID() asn1.ObjectIdentifier {
56 defaultMessageDigestAlgorithm.RLock()
57 defer defaultMessageDigestAlgorithm.RUnlock()
58
59 return defaultMessageDigestAlgorithm.oid
60 }
61
62 // SignedData is an opaque data structure for creating signed data payloads
63 type SignedData struct {
64 sd signedData
65 certs []*x509.Certificate
66 data, messageDigest []byte
67 digestOid asn1.ObjectIdentifier
68 encryptionOid asn1.ObjectIdentifier
69 }
70
71 // NewSignedData takes data and initializes a PKCS7 SignedData struct that is
72 // ready to be signed via AddSigner. The digest algorithm is set to SHA1 by default
73 // and can be changed by calling SetDigestAlgorithm.
74 func NewSignedData(data []byte) (*SignedData, error) {
75 content, err := asn1.Marshal(data)
76 if err != nil {
77 return nil, err
78 }
79 ci := contentInfo{
80 ContentType: OIDData,
81 Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
82 }
83 sd := signedData{
84 ContentInfo: ci,
85 Version: 1,
86 }
87 return &SignedData{sd: sd, data: data, digestOid: defaultMessageDigestAlgorithmOID()}, nil
88 }
89
90 // SignerInfoConfig are optional values to include when adding a signer
91 type SignerInfoConfig struct {
92 ExtraSignedAttributes []Attribute
93 ExtraUnsignedAttributes []Attribute
94 }
95
96 type signedData struct {
97 Version int `asn1:"default:1"`
98 DigestAlgorithmIdentifiers []pkix.AlgorithmIdentifier `asn1:"set"`
99 ContentInfo contentInfo
100 Certificates rawCertificates `asn1:"optional,tag:0"`
101 CRLs []pkix.CertificateList `asn1:"optional,tag:1"`
102 SignerInfos []signerInfo `asn1:"set"`
103 }
104
105 type signerInfo struct {
106 Version int `asn1:"default:1"`
107 IssuerAndSerialNumber issuerAndSerial
108 DigestAlgorithm pkix.AlgorithmIdentifier
109 AuthenticatedAttributes []attribute `asn1:"optional,omitempty,tag:0"`
110 DigestEncryptionAlgorithm pkix.AlgorithmIdentifier
111 EncryptedDigest []byte
112 UnauthenticatedAttributes []attribute `asn1:"optional,omitempty,tag:1"`
113 }
114
115 type attribute struct {
116 Type asn1.ObjectIdentifier
117 Value asn1.RawValue `asn1:"set"`
118 }
119
120 func marshalAttributes(attrs []attribute) ([]byte, error) {
121 encodedAttributes, err := asn1.Marshal(struct {
122 A []attribute `asn1:"set"`
123 }{A: attrs})
124 if err != nil {
125 return nil, err
126 }
127
128 // Remove the leading sequence octets
129 var raw asn1.RawValue
130 asn1.Unmarshal(encodedAttributes, &raw)
131 return raw.Bytes, nil
132 }
133
134 type rawCertificates struct {
135 Raw asn1.RawContent
136 }
137
138 type issuerAndSerial struct {
139 IssuerName asn1.RawValue
140 SerialNumber *big.Int
141 }
142
143 // SetDigestAlgorithm sets the digest algorithm to be used in the signing process.
144 //
145 // This should be called before adding signers
146 func (sd *SignedData) SetDigestAlgorithm(d asn1.ObjectIdentifier) {
147 sd.digestOid = d
148 }
149
150 // SetEncryptionAlgorithm sets the encryption algorithm to be used in the signing process.
151 //
152 // This should be called before adding signers
153 func (sd *SignedData) SetEncryptionAlgorithm(d asn1.ObjectIdentifier) {
154 sd.encryptionOid = d
155 }
156
157 // AddSigner is a wrapper around AddSignerChain() that adds a signer without any parent.
158 func (sd *SignedData) AddSigner(ee *x509.Certificate, pkey crypto.PrivateKey, config SignerInfoConfig) error {
159 var parents []*x509.Certificate
160 return sd.AddSignerChain(ee, pkey, parents, config)
161 }
162
163 // AddSignerChain signs attributes about the content and adds certificates
164 // and signers infos to the Signed Data. The certificate and private key
165 // of the end-entity signer are used to issue the signature, and any
166 // parent of that end-entity that need to be added to the list of
167 // certifications can be specified in the parents slice.
168 //
169 // The signature algorithm used to hash the data is the one of the end-entity
170 // certificate.
171 func (sd *SignedData) AddSignerChain(ee *x509.Certificate, pkey crypto.PrivateKey, parents []*x509.Certificate, config SignerInfoConfig) error {
172 // Following RFC 2315, 9.2 SignerInfo type, the distinguished name of
173 // the issuer of the end-entity signer is stored in the issuerAndSerialNumber
174 // section of the SignedData.SignerInfo, alongside the serial number of
175 // the end-entity.
176 var ias issuerAndSerial
177 ias.SerialNumber = ee.SerialNumber
178 if len(parents) == 0 {
179 // no parent, the issuer is the end-entity cert itself
180 ias.IssuerName = asn1.RawValue{FullBytes: ee.RawIssuer}
181 } else {
182 err := verifyPartialChain(ee, parents)
183 if err != nil {
184 return err
185 }
186 // the first parent is the issuer
187 ias.IssuerName = asn1.RawValue{FullBytes: parents[0].RawSubject}
188 }
189 sd.sd.DigestAlgorithmIdentifiers = append(sd.sd.DigestAlgorithmIdentifiers,
190 pkix.AlgorithmIdentifier{Algorithm: sd.digestOid},
191 )
192 hash, err := getHashForOID(sd.digestOid)
193 if err != nil {
194 return err
195 }
196 h := hash.New()
197 h.Write(sd.data)
198 sd.messageDigest = h.Sum(nil)
199 encryptionOid, err := getOIDForEncryptionAlgorithm(pkey, sd.digestOid)
200 if err != nil {
201 return err
202 }
203 attrs := &attributes{}
204 attrs.Add(OIDAttributeContentType, sd.sd.ContentInfo.ContentType)
205 attrs.Add(OIDAttributeMessageDigest, sd.messageDigest)
206 attrs.Add(OIDAttributeSigningTime, time.Now().UTC())
207 for _, attr := range config.ExtraSignedAttributes {
208 attrs.Add(attr.Type, attr.Value)
209 }
210 finalAttrs, err := attrs.ForMarshalling()
211 if err != nil {
212 return err
213 }
214 unsignedAttrs := &attributes{}
215 for _, attr := range config.ExtraUnsignedAttributes {
216 unsignedAttrs.Add(attr.Type, attr.Value)
217 }
218 finalUnsignedAttrs, err := unsignedAttrs.ForMarshalling()
219 if err != nil {
220 return err
221 }
222 // create signature of signed attributes
223 signature, err := signAttributes(finalAttrs, pkey, hash)
224 if err != nil {
225 return err
226 }
227 signer := signerInfo{
228 AuthenticatedAttributes: finalAttrs,
229 UnauthenticatedAttributes: finalUnsignedAttrs,
230 DigestAlgorithm: pkix.AlgorithmIdentifier{Algorithm: sd.digestOid},
231 DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{Algorithm: encryptionOid},
232 IssuerAndSerialNumber: ias,
233 EncryptedDigest: signature,
234 Version: 1,
235 }
236 sd.certs = append(sd.certs, ee)
237 if len(parents) > 0 {
238 sd.certs = append(sd.certs, parents...)
239 }
240 sd.sd.SignerInfos = append(sd.sd.SignerInfos, signer)
241 return nil
242 }
243
244 // SignWithoutAttr issues a signature on the content of the pkcs7 SignedData.
245 // Unlike AddSigner/AddSignerChain, it calculates the digest on the data alone
246 // and does not include any signed attributes like timestamp and so on.
247 //
248 // This function is needed to sign old Android APKs, something you probably
249 // shouldn't do unless you're maintaining backward compatibility for old
250 // applications.
251 func (sd *SignedData) SignWithoutAttr(ee *x509.Certificate, pkey crypto.PrivateKey, config SignerInfoConfig) error {
252 var signature []byte
253 sd.sd.DigestAlgorithmIdentifiers = append(sd.sd.DigestAlgorithmIdentifiers, pkix.AlgorithmIdentifier{Algorithm: sd.digestOid})
254 hash, err := getHashForOID(sd.digestOid)
255 if err != nil {
256 return err
257 }
258 h := hash.New()
259 h.Write(sd.data)
260 sd.messageDigest = h.Sum(nil)
261 switch pkey := pkey.(type) {
262 case *dsa.PrivateKey:
263 // dsa doesn't implement crypto.Signer so we make a special case
264 // https://github.com/golang/go/issues/27889
265 r, s, err := dsa.Sign(rand.Reader, pkey, sd.messageDigest)
266 if err != nil {
267 return err
268 }
269 signature, err = asn1.Marshal(dsaSignature{r, s})
270 if err != nil {
271 return err
272 }
273 default:
274 key, ok := pkey.(crypto.Signer)
275 if !ok {
276 return errors.New("pkcs7: private key does not implement crypto.Signer")
277 }
278 signature, err = key.Sign(rand.Reader, sd.messageDigest, hash)
279 if err != nil {
280 return err
281 }
282 }
283 var ias issuerAndSerial
284 ias.SerialNumber = ee.SerialNumber
285 // no parent, the issue is the end-entity cert itself
286 ias.IssuerName = asn1.RawValue{FullBytes: ee.RawIssuer}
287 if sd.encryptionOid == nil {
288 // if the encryption algorithm wasn't set by SetEncryptionAlgorithm,
289 // infer it from the digest algorithm
290 sd.encryptionOid, err = getOIDForEncryptionAlgorithm(pkey, sd.digestOid)
291 }
292 if err != nil {
293 return err
294 }
295 signer := signerInfo{
296 DigestAlgorithm: pkix.AlgorithmIdentifier{Algorithm: sd.digestOid},
297 DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{Algorithm: sd.encryptionOid},
298 IssuerAndSerialNumber: ias,
299 EncryptedDigest: signature,
300 Version: 1,
301 }
302 // create signature of signed attributes
303 sd.certs = append(sd.certs, ee)
304 sd.sd.SignerInfos = append(sd.sd.SignerInfos, signer)
305 return nil
306 }
307
308 func (si *signerInfo) SetUnauthenticatedAttributes(extraUnsignedAttrs []Attribute) error {
309 unsignedAttrs := &attributes{}
310 for _, attr := range extraUnsignedAttrs {
311 unsignedAttrs.Add(attr.Type, attr.Value)
312 }
313 finalUnsignedAttrs, err := unsignedAttrs.ForMarshalling()
314 if err != nil {
315 return err
316 }
317
318 si.UnauthenticatedAttributes = finalUnsignedAttrs
319
320 return nil
321 }
322
323 // AddCertificate adds the certificate to the payload. Useful for parent certificates
324 func (sd *SignedData) AddCertificate(cert *x509.Certificate) {
325 sd.certs = append(sd.certs, cert)
326 }
327
328 // Detach removes content from the signed data struct to make it a detached signature.
329 // This must be called right before Finish()
330 func (sd *SignedData) Detach() {
331 sd.sd.ContentInfo = contentInfo{ContentType: OIDData}
332 }
333
334 // GetSignedData returns the private Signed Data
335 func (sd *SignedData) GetSignedData() *signedData {
336 return &sd.sd
337 }
338
339 // Finish marshals the content and its signers
340 func (sd *SignedData) Finish() ([]byte, error) {
341 sd.sd.Certificates = marshalCertificates(sd.certs)
342 inner, err := asn1.Marshal(sd.sd)
343 if err != nil {
344 return nil, err
345 }
346 outer := contentInfo{
347 ContentType: OIDSignedData,
348 Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: inner, IsCompound: true},
349 }
350 return asn1.Marshal(outer)
351 }
352
353 // RemoveAuthenticatedAttributes removes authenticated attributes from signedData
354 // similar to OpenSSL's PKCS7_NOATTR or -noattr flags
355 func (sd *SignedData) RemoveAuthenticatedAttributes() {
356 for i := range sd.sd.SignerInfos {
357 sd.sd.SignerInfos[i].AuthenticatedAttributes = nil
358 }
359 }
360
361 // RemoveUnauthenticatedAttributes removes unauthenticated attributes from signedData
362 func (sd *SignedData) RemoveUnauthenticatedAttributes() {
363 for i := range sd.sd.SignerInfos {
364 sd.sd.SignerInfos[i].UnauthenticatedAttributes = nil
365 }
366 }
367
368 // verifyPartialChain checks that a given cert is issued by the first parent in the list,
369 // then continue down the path. It doesn't require the last parent to be a root CA,
370 // or to be trusted in any truststore. It simply verifies that the chain provided, albeit
371 // partial, makes sense.
372 func verifyPartialChain(cert *x509.Certificate, parents []*x509.Certificate) error {
373 if len(parents) == 0 {
374 return fmt.Errorf("pkcs7: zero parents provided to verify the signature of certificate %q", cert.Subject.CommonName)
375 }
376 err := cert.CheckSignatureFrom(parents[0])
377 if err != nil {
378 return fmt.Errorf("pkcs7: certificate signature from parent is invalid: %v", err)
379 }
380 if len(parents) == 1 {
381 // there is no more parent to check, return
382 return nil
383 }
384 return verifyPartialChain(parents[0], parents[1:])
385 }
386
387 func cert2issuerAndSerial(cert *x509.Certificate) (issuerAndSerial, error) {
388 var ias issuerAndSerial
389 // The issuer RDNSequence has to match exactly the sequence in the certificate
390 // We cannot use cert.Issuer.ToRDNSequence() here since it mangles the sequence
391 ias.IssuerName = asn1.RawValue{FullBytes: cert.RawIssuer}
392 ias.SerialNumber = cert.SerialNumber
393
394 return ias, nil
395 }
396
397 // signs the DER encoded form of the attributes with the private key
398 func signAttributes(attrs []attribute, pkey crypto.PrivateKey, digestAlg crypto.Hash) ([]byte, error) {
399 attrBytes, err := marshalAttributes(attrs)
400 if err != nil {
401 return nil, err
402 }
403 h := digestAlg.New()
404 h.Write(attrBytes)
405 hash := h.Sum(nil)
406
407 // dsa doesn't implement crypto.Signer so we make a special case
408 // https://github.com/golang/go/issues/27889
409 switch pkey := pkey.(type) {
410 case *dsa.PrivateKey:
411 r, s, err := dsa.Sign(rand.Reader, pkey, hash)
412 if err != nil {
413 return nil, err
414 }
415 return asn1.Marshal(dsaSignature{r, s})
416 }
417
418 key, ok := pkey.(crypto.Signer)
419 if !ok {
420 return nil, errors.New("pkcs7: private key does not implement crypto.Signer")
421 }
422 return key.Sign(rand.Reader, hash, digestAlg)
423 }
424
425 type dsaSignature struct {
426 R, S *big.Int
427 }
428
429 // concats and wraps the certificates in the RawValue structure
430 func marshalCertificates(certs []*x509.Certificate) rawCertificates {
431 var buf bytes.Buffer
432 for _, cert := range certs {
433 buf.Write(cert.Raw)
434 }
435 rawCerts, _ := marshalCertificateBytes(buf.Bytes())
436 return rawCerts
437 }
438
439 // Even though, the tag & length are stripped out during marshalling the
440 // RawContent, we have to encode it into the RawContent. If its missing,
441 // then `asn1.Marshal()` will strip out the certificate wrapper instead.
442 func marshalCertificateBytes(certs []byte) (rawCertificates, error) {
443 var val = asn1.RawValue{Bytes: certs, Class: 2, Tag: 0, IsCompound: true}
444 b, err := asn1.Marshal(val)
445 if err != nil {
446 return rawCertificates{}, err
447 }
448 return rawCertificates{Raw: b}, nil
449 }
450
451 // DegenerateCertificate creates a signed data structure containing only the
452 // provided certificate or certificate chain.
453 func DegenerateCertificate(cert []byte) ([]byte, error) {
454 rawCert, err := marshalCertificateBytes(cert)
455 if err != nil {
456 return nil, err
457 }
458 emptyContent := contentInfo{ContentType: OIDData}
459 sd := signedData{
460 Version: 1,
461 ContentInfo: emptyContent,
462 Certificates: rawCert,
463 CRLs: []pkix.CertificateList{},
464 }
465 content, err := asn1.Marshal(sd)
466 if err != nil {
467 return nil, err
468 }
469 signedContent := contentInfo{
470 ContentType: OIDSignedData,
471 Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
472 }
473 return asn1.Marshal(signedContent)
474 }