Debian Codegraph @

sign.go

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