]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/x509/x509.go
Revert "crypto/x509: fix duplicate import"
[gostls13.git] / src / crypto / x509 / x509.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package x509 parses X.509-encoded keys and certificates.
6 package x509
7
8 import (
9         "bytes"
10         "crypto"
11         "crypto/dsa"
12         "crypto/ecdsa"
13         "crypto/ed25519"
14         "crypto/elliptic"
15         "crypto/rsa"
16         "crypto/sha1"
17         "crypto/x509/pkix"
18         "encoding/asn1"
19         "encoding/pem"
20         "errors"
21         "fmt"
22         "io"
23         "math/big"
24         "net"
25         "net/url"
26         "strconv"
27         "strings"
28         "time"
29         "unicode"
30
31         _ "crypto/sha1"
32         _ "crypto/sha256"
33         _ "crypto/sha512"
34
35         "golang.org/x/crypto/cryptobyte"
36         cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
37 )
38
39 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
40 // in RFC 3280.
41 type pkixPublicKey struct {
42         Algo      pkix.AlgorithmIdentifier
43         BitString asn1.BitString
44 }
45
46 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
47 // The encoded public key is a SubjectPublicKeyInfo structure
48 // (see RFC 5280, Section 4.1).
49 //
50 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
51 // ed25519.PublicKey. More types might be supported in the future.
52 //
53 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
54 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
55         var pki publicKeyInfo
56         if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
57                 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
58                         return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
59                 }
60                 return nil, err
61         } else if len(rest) != 0 {
62                 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
63         }
64         algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
65         if algo == UnknownPublicKeyAlgorithm {
66                 return nil, errors.New("x509: unknown public key algorithm")
67         }
68         return parsePublicKey(algo, &pki)
69 }
70
71 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
72         switch pub := pub.(type) {
73         case *rsa.PublicKey:
74                 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
75                         N: pub.N,
76                         E: pub.E,
77                 })
78                 if err != nil {
79                         return nil, pkix.AlgorithmIdentifier{}, err
80                 }
81                 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
82                 // This is a NULL parameters value which is required by
83                 // RFC 3279, Section 2.3.1.
84                 publicKeyAlgorithm.Parameters = asn1.NullRawValue
85         case *ecdsa.PublicKey:
86                 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
87                 oid, ok := oidFromNamedCurve(pub.Curve)
88                 if !ok {
89                         return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
90                 }
91                 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
92                 var paramBytes []byte
93                 paramBytes, err = asn1.Marshal(oid)
94                 if err != nil {
95                         return
96                 }
97                 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
98         case ed25519.PublicKey:
99                 publicKeyBytes = pub
100                 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
101         default:
102                 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
103         }
104
105         return publicKeyBytes, publicKeyAlgorithm, nil
106 }
107
108 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
109 // The encoded public key is a SubjectPublicKeyInfo structure
110 // (see RFC 5280, Section 4.1).
111 //
112 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
113 // and ed25519.PublicKey. Unsupported key types result in an error.
114 //
115 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
116 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
117         var publicKeyBytes []byte
118         var publicKeyAlgorithm pkix.AlgorithmIdentifier
119         var err error
120
121         if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
122                 return nil, err
123         }
124
125         pkix := pkixPublicKey{
126                 Algo: publicKeyAlgorithm,
127                 BitString: asn1.BitString{
128                         Bytes:     publicKeyBytes,
129                         BitLength: 8 * len(publicKeyBytes),
130                 },
131         }
132
133         ret, _ := asn1.Marshal(pkix)
134         return ret, nil
135 }
136
137 // These structures reflect the ASN.1 structure of X.509 certificates.:
138
139 type certificate struct {
140         Raw                asn1.RawContent
141         TBSCertificate     tbsCertificate
142         SignatureAlgorithm pkix.AlgorithmIdentifier
143         SignatureValue     asn1.BitString
144 }
145
146 type tbsCertificate struct {
147         Raw                asn1.RawContent
148         Version            int `asn1:"optional,explicit,default:0,tag:0"`
149         SerialNumber       *big.Int
150         SignatureAlgorithm pkix.AlgorithmIdentifier
151         Issuer             asn1.RawValue
152         Validity           validity
153         Subject            asn1.RawValue
154         PublicKey          publicKeyInfo
155         UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
156         SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
157         Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
158 }
159
160 type dsaAlgorithmParameters struct {
161         P, Q, G *big.Int
162 }
163
164 type validity struct {
165         NotBefore, NotAfter time.Time
166 }
167
168 type publicKeyInfo struct {
169         Raw       asn1.RawContent
170         Algorithm pkix.AlgorithmIdentifier
171         PublicKey asn1.BitString
172 }
173
174 // RFC 5280,  4.2.1.1
175 type authKeyId struct {
176         Id []byte `asn1:"optional,tag:0"`
177 }
178
179 type SignatureAlgorithm int
180
181 const (
182         UnknownSignatureAlgorithm SignatureAlgorithm = iota
183
184         MD2WithRSA // Unsupported.
185         MD5WithRSA // Only supported for signing, not verification.
186         SHA1WithRSA
187         SHA256WithRSA
188         SHA384WithRSA
189         SHA512WithRSA
190         DSAWithSHA1   // Unsupported.
191         DSAWithSHA256 // Unsupported.
192         ECDSAWithSHA1
193         ECDSAWithSHA256
194         ECDSAWithSHA384
195         ECDSAWithSHA512
196         SHA256WithRSAPSS
197         SHA384WithRSAPSS
198         SHA512WithRSAPSS
199         PureEd25519
200 )
201
202 func (algo SignatureAlgorithm) isRSAPSS() bool {
203         switch algo {
204         case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
205                 return true
206         default:
207                 return false
208         }
209 }
210
211 func (algo SignatureAlgorithm) String() string {
212         for _, details := range signatureAlgorithmDetails {
213                 if details.algo == algo {
214                         return details.name
215                 }
216         }
217         return strconv.Itoa(int(algo))
218 }
219
220 type PublicKeyAlgorithm int
221
222 const (
223         UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
224         RSA
225         DSA // Unsupported.
226         ECDSA
227         Ed25519
228 )
229
230 var publicKeyAlgoName = [...]string{
231         RSA:     "RSA",
232         DSA:     "DSA",
233         ECDSA:   "ECDSA",
234         Ed25519: "Ed25519",
235 }
236
237 func (algo PublicKeyAlgorithm) String() string {
238         if 0 < algo && int(algo) < len(publicKeyAlgoName) {
239                 return publicKeyAlgoName[algo]
240         }
241         return strconv.Itoa(int(algo))
242 }
243
244 // OIDs for signature algorithms
245 //
246 // pkcs-1 OBJECT IDENTIFIER ::= {
247 //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
248 //
249 //
250 // RFC 3279 2.2.1 RSA Signature Algorithms
251 //
252 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
253 //
254 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
255 //
256 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
257 //
258 // dsaWithSha1 OBJECT IDENTIFIER ::= {
259 //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
260 //
261 // RFC 3279 2.2.3 ECDSA Signature Algorithm
262 //
263 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
264 //        iso(1) member-body(2) us(840) ansi-x962(10045)
265 //    signatures(4) ecdsa-with-SHA1(1)}
266 //
267 //
268 // RFC 4055 5 PKCS #1 Version 1.5
269 //
270 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
271 //
272 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
273 //
274 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
275 //
276 //
277 // RFC 5758 3.1 DSA Signature Algorithms
278 //
279 // dsaWithSha256 OBJECT IDENTIFIER ::= {
280 //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
281 //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
282 //
283 // RFC 5758 3.2 ECDSA Signature Algorithm
284 //
285 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
286 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
287 //
288 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
289 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
290 //
291 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
293 //
294 //
295 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
296 //
297 // id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
298
299 var (
300         oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
301         oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
302         oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
303         oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
304         oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
305         oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
306         oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
307         oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
308         oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
309         oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
310         oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
311         oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
312         oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
313         oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
314
315         oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
316         oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
317         oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
318
319         oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
320
321         // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
322         // but it's specified by ISO. Microsoft's makecert.exe has been known
323         // to produce certificates with this OID.
324         oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
325 )
326
327 var signatureAlgorithmDetails = []struct {
328         algo       SignatureAlgorithm
329         name       string
330         oid        asn1.ObjectIdentifier
331         pubKeyAlgo PublicKeyAlgorithm
332         hash       crypto.Hash
333 }{
334         {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
335         {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
336         {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
337         {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
338         {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
339         {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
340         {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
341         {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
342         {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
343         {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
344         {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
345         {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
346         {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
347         {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
348         {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
349         {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
350         {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
351 }
352
353 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
354 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
355 // The parameters contain the following values:
356 //   * hashAlgorithm contains the associated hash identifier with NULL parameters
357 //   * maskGenAlgorithm always contains the default mgf1SHA1 identifier
358 //   * saltLength contains the length of the associated hash
359 //   * trailerField always contains the default trailerFieldBC value
360 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
361         crypto.SHA256: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}},
362         crypto.SHA384: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}},
363         crypto.SHA512: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}},
364 }
365
366 // pssParameters reflects the parameters in an AlgorithmIdentifier that
367 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
368 type pssParameters struct {
369         // The following three fields are not marked as
370         // optional because the default values specify SHA-1,
371         // which is no longer suitable for use in signatures.
372         Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
373         MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
374         SaltLength   int                      `asn1:"explicit,tag:2"`
375         TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
376 }
377
378 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
379         if ai.Algorithm.Equal(oidSignatureEd25519) {
380                 // RFC 8410, Section 3
381                 // > For all of the OIDs, the parameters MUST be absent.
382                 if len(ai.Parameters.FullBytes) != 0 {
383                         return UnknownSignatureAlgorithm
384                 }
385         }
386
387         if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
388                 for _, details := range signatureAlgorithmDetails {
389                         if ai.Algorithm.Equal(details.oid) {
390                                 return details.algo
391                         }
392                 }
393                 return UnknownSignatureAlgorithm
394         }
395
396         // RSA PSS is special because it encodes important parameters
397         // in the Parameters.
398
399         var params pssParameters
400         if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
401                 return UnknownSignatureAlgorithm
402         }
403
404         var mgf1HashFunc pkix.AlgorithmIdentifier
405         if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
406                 return UnknownSignatureAlgorithm
407         }
408
409         // PSS is greatly overburdened with options. This code forces them into
410         // three buckets by requiring that the MGF1 hash function always match the
411         // message hash function (as recommended in RFC 3447, Section 8.1), that the
412         // salt length matches the hash length, and that the trailer field has the
413         // default value.
414         if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
415                 !params.MGF.Algorithm.Equal(oidMGF1) ||
416                 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
417                 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
418                 params.TrailerField != 1 {
419                 return UnknownSignatureAlgorithm
420         }
421
422         switch {
423         case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
424                 return SHA256WithRSAPSS
425         case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
426                 return SHA384WithRSAPSS
427         case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
428                 return SHA512WithRSAPSS
429         }
430
431         return UnknownSignatureAlgorithm
432 }
433
434 // RFC 3279, 2.3 Public Key Algorithms
435 //
436 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
437 //    rsadsi(113549) pkcs(1) 1 }
438 //
439 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
440 //
441 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
442 //    x9-57(10040) x9cm(4) 1 }
443 //
444 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
445 //
446 // id-ecPublicKey OBJECT IDENTIFIER ::= {
447 //       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
448 var (
449         oidPublicKeyRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
450         oidPublicKeyDSA     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
451         oidPublicKeyECDSA   = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
452         oidPublicKeyEd25519 = oidSignatureEd25519
453 )
454
455 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
456         switch {
457         case oid.Equal(oidPublicKeyRSA):
458                 return RSA
459         case oid.Equal(oidPublicKeyDSA):
460                 return DSA
461         case oid.Equal(oidPublicKeyECDSA):
462                 return ECDSA
463         case oid.Equal(oidPublicKeyEd25519):
464                 return Ed25519
465         }
466         return UnknownPublicKeyAlgorithm
467 }
468
469 // RFC 5480, 2.1.1.1. Named Curve
470 //
471 // secp224r1 OBJECT IDENTIFIER ::= {
472 //   iso(1) identified-organization(3) certicom(132) curve(0) 33 }
473 //
474 // secp256r1 OBJECT IDENTIFIER ::= {
475 //   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
476 //   prime(1) 7 }
477 //
478 // secp384r1 OBJECT IDENTIFIER ::= {
479 //   iso(1) identified-organization(3) certicom(132) curve(0) 34 }
480 //
481 // secp521r1 OBJECT IDENTIFIER ::= {
482 //   iso(1) identified-organization(3) certicom(132) curve(0) 35 }
483 //
484 // NB: secp256r1 is equivalent to prime256v1
485 var (
486         oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
487         oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
488         oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
489         oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
490 )
491
492 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
493         switch {
494         case oid.Equal(oidNamedCurveP224):
495                 return elliptic.P224()
496         case oid.Equal(oidNamedCurveP256):
497                 return elliptic.P256()
498         case oid.Equal(oidNamedCurveP384):
499                 return elliptic.P384()
500         case oid.Equal(oidNamedCurveP521):
501                 return elliptic.P521()
502         }
503         return nil
504 }
505
506 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
507         switch curve {
508         case elliptic.P224():
509                 return oidNamedCurveP224, true
510         case elliptic.P256():
511                 return oidNamedCurveP256, true
512         case elliptic.P384():
513                 return oidNamedCurveP384, true
514         case elliptic.P521():
515                 return oidNamedCurveP521, true
516         }
517
518         return nil, false
519 }
520
521 // KeyUsage represents the set of actions that are valid for a given key. It's
522 // a bitmap of the KeyUsage* constants.
523 type KeyUsage int
524
525 const (
526         KeyUsageDigitalSignature KeyUsage = 1 << iota
527         KeyUsageContentCommitment
528         KeyUsageKeyEncipherment
529         KeyUsageDataEncipherment
530         KeyUsageKeyAgreement
531         KeyUsageCertSign
532         KeyUsageCRLSign
533         KeyUsageEncipherOnly
534         KeyUsageDecipherOnly
535 )
536
537 // RFC 5280, 4.2.1.12  Extended Key Usage
538 //
539 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
540 //
541 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
542 //
543 // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
544 // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
545 // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
546 // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
547 // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
548 // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
549 var (
550         oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
551         oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
552         oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
553         oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
554         oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
555         oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
556         oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
557         oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
558         oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
559         oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
560         oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
561         oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
562         oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
563         oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
564 )
565
566 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
567 // Each of the ExtKeyUsage* constants define a unique action.
568 type ExtKeyUsage int
569
570 const (
571         ExtKeyUsageAny ExtKeyUsage = iota
572         ExtKeyUsageServerAuth
573         ExtKeyUsageClientAuth
574         ExtKeyUsageCodeSigning
575         ExtKeyUsageEmailProtection
576         ExtKeyUsageIPSECEndSystem
577         ExtKeyUsageIPSECTunnel
578         ExtKeyUsageIPSECUser
579         ExtKeyUsageTimeStamping
580         ExtKeyUsageOCSPSigning
581         ExtKeyUsageMicrosoftServerGatedCrypto
582         ExtKeyUsageNetscapeServerGatedCrypto
583         ExtKeyUsageMicrosoftCommercialCodeSigning
584         ExtKeyUsageMicrosoftKernelCodeSigning
585 )
586
587 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
588 var extKeyUsageOIDs = []struct {
589         extKeyUsage ExtKeyUsage
590         oid         asn1.ObjectIdentifier
591 }{
592         {ExtKeyUsageAny, oidExtKeyUsageAny},
593         {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
594         {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
595         {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
596         {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
597         {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
598         {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
599         {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
600         {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
601         {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
602         {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
603         {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
604         {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
605         {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
606 }
607
608 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
609         for _, pair := range extKeyUsageOIDs {
610                 if oid.Equal(pair.oid) {
611                         return pair.extKeyUsage, true
612                 }
613         }
614         return
615 }
616
617 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
618         for _, pair := range extKeyUsageOIDs {
619                 if eku == pair.extKeyUsage {
620                         return pair.oid, true
621                 }
622         }
623         return
624 }
625
626 // A Certificate represents an X.509 certificate.
627 type Certificate struct {
628         Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
629         RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
630         RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
631         RawSubject              []byte // DER encoded Subject
632         RawIssuer               []byte // DER encoded Issuer
633
634         Signature          []byte
635         SignatureAlgorithm SignatureAlgorithm
636
637         PublicKeyAlgorithm PublicKeyAlgorithm
638         PublicKey          interface{}
639
640         Version             int
641         SerialNumber        *big.Int
642         Issuer              pkix.Name
643         Subject             pkix.Name
644         NotBefore, NotAfter time.Time // Validity bounds.
645         KeyUsage            KeyUsage
646
647         // Extensions contains raw X.509 extensions. When parsing certificates,
648         // this can be used to extract non-critical extensions that are not
649         // parsed by this package. When marshaling certificates, the Extensions
650         // field is ignored, see ExtraExtensions.
651         Extensions []pkix.Extension
652
653         // ExtraExtensions contains extensions to be copied, raw, into any
654         // marshaled certificates. Values override any extensions that would
655         // otherwise be produced based on the other fields. The ExtraExtensions
656         // field is not populated when parsing certificates, see Extensions.
657         ExtraExtensions []pkix.Extension
658
659         // UnhandledCriticalExtensions contains a list of extension IDs that
660         // were not (fully) processed when parsing. Verify will fail if this
661         // slice is non-empty, unless verification is delegated to an OS
662         // library which understands all the critical extensions.
663         //
664         // Users can access these extensions using Extensions and can remove
665         // elements from this slice if they believe that they have been
666         // handled.
667         UnhandledCriticalExtensions []asn1.ObjectIdentifier
668
669         ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
670         UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
671
672         // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
673         // and MaxPathLenZero are valid.
674         BasicConstraintsValid bool
675         IsCA                  bool
676
677         // MaxPathLen and MaxPathLenZero indicate the presence and
678         // value of the BasicConstraints' "pathLenConstraint".
679         //
680         // When parsing a certificate, a positive non-zero MaxPathLen
681         // means that the field was specified, -1 means it was unset,
682         // and MaxPathLenZero being true mean that the field was
683         // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
684         // should be treated equivalent to -1 (unset).
685         //
686         // When generating a certificate, an unset pathLenConstraint
687         // can be requested with either MaxPathLen == -1 or using the
688         // zero value for both MaxPathLen and MaxPathLenZero.
689         MaxPathLen int
690         // MaxPathLenZero indicates that BasicConstraintsValid==true
691         // and MaxPathLen==0 should be interpreted as an actual
692         // maximum path length of zero. Otherwise, that combination is
693         // interpreted as MaxPathLen not being set.
694         MaxPathLenZero bool
695
696         SubjectKeyId   []byte
697         AuthorityKeyId []byte
698
699         // RFC 5280, 4.2.2.1 (Authority Information Access)
700         OCSPServer            []string
701         IssuingCertificateURL []string
702
703         // Subject Alternate Name values. (Note that these values may not be valid
704         // if invalid values were contained within a parsed certificate. For
705         // example, an element of DNSNames may not be a valid DNS domain name.)
706         DNSNames       []string
707         EmailAddresses []string
708         IPAddresses    []net.IP
709         URIs           []*url.URL
710
711         // Name constraints
712         PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
713         PermittedDNSDomains         []string
714         ExcludedDNSDomains          []string
715         PermittedIPRanges           []*net.IPNet
716         ExcludedIPRanges            []*net.IPNet
717         PermittedEmailAddresses     []string
718         ExcludedEmailAddresses      []string
719         PermittedURIDomains         []string
720         ExcludedURIDomains          []string
721
722         // CRL Distribution Points
723         CRLDistributionPoints []string
724
725         PolicyIdentifiers []asn1.ObjectIdentifier
726 }
727
728 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
729 // involves algorithms that are not currently implemented.
730 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
731
732 // An InsecureAlgorithmError
733 type InsecureAlgorithmError SignatureAlgorithm
734
735 func (e InsecureAlgorithmError) Error() string {
736         return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
737 }
738
739 // ConstraintViolationError results when a requested usage is not permitted by
740 // a certificate. For example: checking a signature when the public key isn't a
741 // certificate signing key.
742 type ConstraintViolationError struct{}
743
744 func (ConstraintViolationError) Error() string {
745         return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
746 }
747
748 func (c *Certificate) Equal(other *Certificate) bool {
749         if c == nil || other == nil {
750                 return c == other
751         }
752         return bytes.Equal(c.Raw, other.Raw)
753 }
754
755 func (c *Certificate) hasSANExtension() bool {
756         return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
757 }
758
759 // CheckSignatureFrom verifies that the signature on c is a valid signature
760 // from parent.
761 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
762         // RFC 5280, 4.2.1.9:
763         // "If the basic constraints extension is not present in a version 3
764         // certificate, or the extension is present but the cA boolean is not
765         // asserted, then the certified public key MUST NOT be used to verify
766         // certificate signatures."
767         if parent.Version == 3 && !parent.BasicConstraintsValid ||
768                 parent.BasicConstraintsValid && !parent.IsCA {
769                 return ConstraintViolationError{}
770         }
771
772         if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
773                 return ConstraintViolationError{}
774         }
775
776         if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
777                 return ErrUnsupportedAlgorithm
778         }
779
780         // TODO(agl): don't ignore the path length constraint.
781
782         return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
783 }
784
785 // CheckSignature verifies that signature is a valid signature over signed from
786 // c's public key.
787 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
788         return checkSignature(algo, signed, signature, c.PublicKey)
789 }
790
791 func (c *Certificate) hasNameConstraints() bool {
792         return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
793 }
794
795 func (c *Certificate) getSANExtension() []byte {
796         for _, e := range c.Extensions {
797                 if e.Id.Equal(oidExtensionSubjectAltName) {
798                         return e.Value
799                 }
800         }
801         return nil
802 }
803
804 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
805         return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
806 }
807
808 // CheckSignature verifies that signature is a valid signature over signed from
809 // a crypto.PublicKey.
810 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
811         var hashType crypto.Hash
812         var pubKeyAlgo PublicKeyAlgorithm
813
814         for _, details := range signatureAlgorithmDetails {
815                 if details.algo == algo {
816                         hashType = details.hash
817                         pubKeyAlgo = details.pubKeyAlgo
818                 }
819         }
820
821         switch hashType {
822         case crypto.Hash(0):
823                 if pubKeyAlgo != Ed25519 {
824                         return ErrUnsupportedAlgorithm
825                 }
826         case crypto.MD5:
827                 return InsecureAlgorithmError(algo)
828         default:
829                 if !hashType.Available() {
830                         return ErrUnsupportedAlgorithm
831                 }
832                 h := hashType.New()
833                 h.Write(signed)
834                 signed = h.Sum(nil)
835         }
836
837         switch pub := publicKey.(type) {
838         case *rsa.PublicKey:
839                 if pubKeyAlgo != RSA {
840                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
841                 }
842                 if algo.isRSAPSS() {
843                         return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
844                 } else {
845                         return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
846                 }
847         case *ecdsa.PublicKey:
848                 if pubKeyAlgo != ECDSA {
849                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
850                 }
851                 if !ecdsa.VerifyASN1(pub, signed, signature) {
852                         return errors.New("x509: ECDSA verification failure")
853                 }
854                 return
855         case ed25519.PublicKey:
856                 if pubKeyAlgo != Ed25519 {
857                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
858                 }
859                 if !ed25519.Verify(pub, signed, signature) {
860                         return errors.New("x509: Ed25519 verification failure")
861                 }
862                 return
863         }
864         return ErrUnsupportedAlgorithm
865 }
866
867 // CheckCRLSignature checks that the signature in crl is from c.
868 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
869         algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
870         return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
871 }
872
873 type UnhandledCriticalExtension struct{}
874
875 func (h UnhandledCriticalExtension) Error() string {
876         return "x509: unhandled critical extension"
877 }
878
879 type basicConstraints struct {
880         IsCA       bool `asn1:"optional"`
881         MaxPathLen int  `asn1:"optional,default:-1"`
882 }
883
884 // RFC 5280 4.2.1.4
885 type policyInformation struct {
886         Policy asn1.ObjectIdentifier
887         // policyQualifiers omitted
888 }
889
890 const (
891         nameTypeEmail = 1
892         nameTypeDNS   = 2
893         nameTypeURI   = 6
894         nameTypeIP    = 7
895 )
896
897 // RFC 5280, 4.2.2.1
898 type authorityInfoAccess struct {
899         Method   asn1.ObjectIdentifier
900         Location asn1.RawValue
901 }
902
903 // RFC 5280, 4.2.1.14
904 type distributionPoint struct {
905         DistributionPoint distributionPointName `asn1:"optional,tag:0"`
906         Reason            asn1.BitString        `asn1:"optional,tag:1"`
907         CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
908 }
909
910 type distributionPointName struct {
911         FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
912         RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
913 }
914
915 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
916         asn1Data := keyData.PublicKey.RightAlign()
917         switch algo {
918         case RSA:
919                 // RSA public keys must have a NULL in the parameters.
920                 // See RFC 3279, Section 2.3.1.
921                 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
922                         return nil, errors.New("x509: RSA key missing NULL parameters")
923                 }
924
925                 p := new(pkcs1PublicKey)
926                 rest, err := asn1.Unmarshal(asn1Data, p)
927                 if err != nil {
928                         return nil, err
929                 }
930                 if len(rest) != 0 {
931                         return nil, errors.New("x509: trailing data after RSA public key")
932                 }
933
934                 if p.N.Sign() <= 0 {
935                         return nil, errors.New("x509: RSA modulus is not a positive number")
936                 }
937                 if p.E <= 0 {
938                         return nil, errors.New("x509: RSA public exponent is not a positive number")
939                 }
940
941                 pub := &rsa.PublicKey{
942                         E: p.E,
943                         N: p.N,
944                 }
945                 return pub, nil
946         case DSA:
947                 var p *big.Int
948                 rest, err := asn1.Unmarshal(asn1Data, &p)
949                 if err != nil {
950                         return nil, err
951                 }
952                 if len(rest) != 0 {
953                         return nil, errors.New("x509: trailing data after DSA public key")
954                 }
955                 paramsData := keyData.Algorithm.Parameters.FullBytes
956                 params := new(dsaAlgorithmParameters)
957                 rest, err = asn1.Unmarshal(paramsData, params)
958                 if err != nil {
959                         return nil, err
960                 }
961                 if len(rest) != 0 {
962                         return nil, errors.New("x509: trailing data after DSA parameters")
963                 }
964                 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
965                         return nil, errors.New("x509: zero or negative DSA parameter")
966                 }
967                 pub := &dsa.PublicKey{
968                         Parameters: dsa.Parameters{
969                                 P: params.P,
970                                 Q: params.Q,
971                                 G: params.G,
972                         },
973                         Y: p,
974                 }
975                 return pub, nil
976         case ECDSA:
977                 paramsData := keyData.Algorithm.Parameters.FullBytes
978                 namedCurveOID := new(asn1.ObjectIdentifier)
979                 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
980                 if err != nil {
981                         return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
982                 }
983                 if len(rest) != 0 {
984                         return nil, errors.New("x509: trailing data after ECDSA parameters")
985                 }
986                 namedCurve := namedCurveFromOID(*namedCurveOID)
987                 if namedCurve == nil {
988                         return nil, errors.New("x509: unsupported elliptic curve")
989                 }
990                 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
991                 if x == nil {
992                         return nil, errors.New("x509: failed to unmarshal elliptic curve point")
993                 }
994                 pub := &ecdsa.PublicKey{
995                         Curve: namedCurve,
996                         X:     x,
997                         Y:     y,
998                 }
999                 return pub, nil
1000         case Ed25519:
1001                 // RFC 8410, Section 3
1002                 // > For all of the OIDs, the parameters MUST be absent.
1003                 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1004                         return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1005                 }
1006                 if len(asn1Data) != ed25519.PublicKeySize {
1007                         return nil, errors.New("x509: wrong Ed25519 public key size")
1008                 }
1009                 pub := make([]byte, ed25519.PublicKeySize)
1010                 copy(pub, asn1Data)
1011                 return ed25519.PublicKey(pub), nil
1012         default:
1013                 return nil, nil
1014         }
1015 }
1016
1017 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1018         // RFC 5280, 4.2.1.6
1019
1020         // SubjectAltName ::= GeneralNames
1021         //
1022         // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1023         //
1024         // GeneralName ::= CHOICE {
1025         //      otherName                       [0]     OtherName,
1026         //      rfc822Name                      [1]     IA5String,
1027         //      dNSName                         [2]     IA5String,
1028         //      x400Address                     [3]     ORAddress,
1029         //      directoryName                   [4]     Name,
1030         //      ediPartyName                    [5]     EDIPartyName,
1031         //      uniformResourceIdentifier       [6]     IA5String,
1032         //      iPAddress                       [7]     OCTET STRING,
1033         //      registeredID                    [8]     OBJECT IDENTIFIER }
1034         var seq asn1.RawValue
1035         rest, err := asn1.Unmarshal(extension, &seq)
1036         if err != nil {
1037                 return err
1038         } else if len(rest) != 0 {
1039                 return errors.New("x509: trailing data after X.509 extension")
1040         }
1041         if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1042                 return asn1.StructuralError{Msg: "bad SAN sequence"}
1043         }
1044
1045         rest = seq.Bytes
1046         for len(rest) > 0 {
1047                 var v asn1.RawValue
1048                 rest, err = asn1.Unmarshal(rest, &v)
1049                 if err != nil {
1050                         return err
1051                 }
1052
1053                 if err := callback(v.Tag, v.Bytes); err != nil {
1054                         return err
1055                 }
1056         }
1057
1058         return nil
1059 }
1060
1061 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1062         err = forEachSAN(value, func(tag int, data []byte) error {
1063                 switch tag {
1064                 case nameTypeEmail:
1065                         email := string(data)
1066                         if err := isIA5String(email); err != nil {
1067                                 return errors.New("x509: SAN rfc822Name is malformed")
1068                         }
1069                         emailAddresses = append(emailAddresses, email)
1070                 case nameTypeDNS:
1071                         name := string(data)
1072                         if err := isIA5String(name); err != nil {
1073                                 return errors.New("x509: SAN dNSName is malformed")
1074                         }
1075                         dnsNames = append(dnsNames, string(name))
1076                 case nameTypeURI:
1077                         uriStr := string(data)
1078                         if err := isIA5String(uriStr); err != nil {
1079                                 return errors.New("x509: SAN uniformResourceIdentifier is malformed")
1080                         }
1081                         uri, err := url.Parse(uriStr)
1082                         if err != nil {
1083                                 return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err)
1084                         }
1085                         if len(uri.Host) > 0 {
1086                                 if _, ok := domainToReverseLabels(uri.Host); !ok {
1087                                         return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr)
1088                                 }
1089                         }
1090                         uris = append(uris, uri)
1091                 case nameTypeIP:
1092                         switch len(data) {
1093                         case net.IPv4len, net.IPv6len:
1094                                 ipAddresses = append(ipAddresses, data)
1095                         default:
1096                                 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1097                         }
1098                 }
1099
1100                 return nil
1101         })
1102
1103         return
1104 }
1105
1106 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1107 func isValidIPMask(mask []byte) bool {
1108         seenZero := false
1109
1110         for _, b := range mask {
1111                 if seenZero {
1112                         if b != 0 {
1113                                 return false
1114                         }
1115
1116                         continue
1117                 }
1118
1119                 switch b {
1120                 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1121                         seenZero = true
1122                 case 0xff:
1123                 default:
1124                         return false
1125                 }
1126         }
1127
1128         return true
1129 }
1130
1131 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1132         // RFC 5280, 4.2.1.10
1133
1134         // NameConstraints ::= SEQUENCE {
1135         //      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
1136         //      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
1137         //
1138         // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1139         //
1140         // GeneralSubtree ::= SEQUENCE {
1141         //      base                    GeneralName,
1142         //      minimum         [0]     BaseDistance DEFAULT 0,
1143         //      maximum         [1]     BaseDistance OPTIONAL }
1144         //
1145         // BaseDistance ::= INTEGER (0..MAX)
1146
1147         outer := cryptobyte.String(e.Value)
1148         var toplevel, permitted, excluded cryptobyte.String
1149         var havePermitted, haveExcluded bool
1150         if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1151                 !outer.Empty() ||
1152                 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1153                 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1154                 !toplevel.Empty() {
1155                 return false, errors.New("x509: invalid NameConstraints extension")
1156         }
1157
1158         if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1159                 // From RFC 5280, Section 4.2.1.10:
1160                 //   “either the permittedSubtrees field
1161                 //   or the excludedSubtrees MUST be
1162                 //   present”
1163                 return false, errors.New("x509: empty name constraints extension")
1164         }
1165
1166         getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1167                 for !subtrees.Empty() {
1168                         var seq, value cryptobyte.String
1169                         var tag cryptobyte_asn1.Tag
1170                         if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1171                                 !seq.ReadAnyASN1(&value, &tag) {
1172                                 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1173                         }
1174
1175                         var (
1176                                 dnsTag   = cryptobyte_asn1.Tag(2).ContextSpecific()
1177                                 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1178                                 ipTag    = cryptobyte_asn1.Tag(7).ContextSpecific()
1179                                 uriTag   = cryptobyte_asn1.Tag(6).ContextSpecific()
1180                         )
1181
1182                         switch tag {
1183                         case dnsTag:
1184                                 domain := string(value)
1185                                 if err := isIA5String(domain); err != nil {
1186                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1187                                 }
1188
1189                                 trimmedDomain := domain
1190                                 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1191                                         // constraints can have a leading
1192                                         // period to exclude the domain
1193                                         // itself, but that's not valid in a
1194                                         // normal domain name.
1195                                         trimmedDomain = trimmedDomain[1:]
1196                                 }
1197                                 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1198                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1199                                 }
1200                                 dnsNames = append(dnsNames, domain)
1201
1202                         case ipTag:
1203                                 l := len(value)
1204                                 var ip, mask []byte
1205
1206                                 switch l {
1207                                 case 8:
1208                                         ip = value[:4]
1209                                         mask = value[4:]
1210
1211                                 case 32:
1212                                         ip = value[:16]
1213                                         mask = value[16:]
1214
1215                                 default:
1216                                         return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1217                                 }
1218
1219                                 if !isValidIPMask(mask) {
1220                                         return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1221                                 }
1222
1223                                 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1224
1225                         case emailTag:
1226                                 constraint := string(value)
1227                                 if err := isIA5String(constraint); err != nil {
1228                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1229                                 }
1230
1231                                 // If the constraint contains an @ then
1232                                 // it specifies an exact mailbox name.
1233                                 if strings.Contains(constraint, "@") {
1234                                         if _, ok := parseRFC2821Mailbox(constraint); !ok {
1235                                                 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1236                                         }
1237                                 } else {
1238                                         // Otherwise it's a domain name.
1239                                         domain := constraint
1240                                         if len(domain) > 0 && domain[0] == '.' {
1241                                                 domain = domain[1:]
1242                                         }
1243                                         if _, ok := domainToReverseLabels(domain); !ok {
1244                                                 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1245                                         }
1246                                 }
1247                                 emails = append(emails, constraint)
1248
1249                         case uriTag:
1250                                 domain := string(value)
1251                                 if err := isIA5String(domain); err != nil {
1252                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1253                                 }
1254
1255                                 if net.ParseIP(domain) != nil {
1256                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1257                                 }
1258
1259                                 trimmedDomain := domain
1260                                 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1261                                         // constraints can have a leading
1262                                         // period to exclude the domain itself,
1263                                         // but that's not valid in a normal
1264                                         // domain name.
1265                                         trimmedDomain = trimmedDomain[1:]
1266                                 }
1267                                 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1268                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1269                                 }
1270                                 uriDomains = append(uriDomains, domain)
1271
1272                         default:
1273                                 unhandled = true
1274                         }
1275                 }
1276
1277                 return dnsNames, ips, emails, uriDomains, nil
1278         }
1279
1280         if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1281                 return false, err
1282         }
1283         if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1284                 return false, err
1285         }
1286         out.PermittedDNSDomainsCritical = e.Critical
1287
1288         return unhandled, nil
1289 }
1290
1291 func parseCertificate(in *certificate) (*Certificate, error) {
1292         out := new(Certificate)
1293         out.Raw = in.Raw
1294         out.RawTBSCertificate = in.TBSCertificate.Raw
1295         out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1296         out.RawSubject = in.TBSCertificate.Subject.FullBytes
1297         out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1298
1299         out.Signature = in.SignatureValue.RightAlign()
1300         out.SignatureAlgorithm =
1301                 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1302
1303         out.PublicKeyAlgorithm =
1304                 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1305         var err error
1306         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1307         if err != nil {
1308                 return nil, err
1309         }
1310
1311         out.Version = in.TBSCertificate.Version + 1
1312         out.SerialNumber = in.TBSCertificate.SerialNumber
1313
1314         var issuer, subject pkix.RDNSequence
1315         if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1316                 return nil, err
1317         } else if len(rest) != 0 {
1318                 return nil, errors.New("x509: trailing data after X.509 subject")
1319         }
1320         if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1321                 return nil, err
1322         } else if len(rest) != 0 {
1323                 return nil, errors.New("x509: trailing data after X.509 issuer")
1324         }
1325
1326         out.Issuer.FillFromRDNSequence(&issuer)
1327         out.Subject.FillFromRDNSequence(&subject)
1328
1329         out.NotBefore = in.TBSCertificate.Validity.NotBefore
1330         out.NotAfter = in.TBSCertificate.Validity.NotAfter
1331
1332         for _, e := range in.TBSCertificate.Extensions {
1333                 out.Extensions = append(out.Extensions, e)
1334                 unhandled := false
1335
1336                 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1337                         switch e.Id[3] {
1338                         case 15:
1339                                 // RFC 5280, 4.2.1.3
1340                                 var usageBits asn1.BitString
1341                                 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1342                                         return nil, err
1343                                 } else if len(rest) != 0 {
1344                                         return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1345                                 }
1346
1347                                 var usage int
1348                                 for i := 0; i < 9; i++ {
1349                                         if usageBits.At(i) != 0 {
1350                                                 usage |= 1 << uint(i)
1351                                         }
1352                                 }
1353                                 out.KeyUsage = KeyUsage(usage)
1354
1355                         case 19:
1356                                 // RFC 5280, 4.2.1.9
1357                                 var constraints basicConstraints
1358                                 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1359                                         return nil, err
1360                                 } else if len(rest) != 0 {
1361                                         return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1362                                 }
1363
1364                                 out.BasicConstraintsValid = true
1365                                 out.IsCA = constraints.IsCA
1366                                 out.MaxPathLen = constraints.MaxPathLen
1367                                 out.MaxPathLenZero = out.MaxPathLen == 0
1368                                 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1369                         case 17:
1370                                 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1371                                 if err != nil {
1372                                         return nil, err
1373                                 }
1374
1375                                 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1376                                         // If we didn't parse anything then we do the critical check, below.
1377                                         unhandled = true
1378                                 }
1379
1380                         case 30:
1381                                 unhandled, err = parseNameConstraintsExtension(out, e)
1382                                 if err != nil {
1383                                         return nil, err
1384                                 }
1385
1386                         case 31:
1387                                 // RFC 5280, 4.2.1.13
1388
1389                                 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1390                                 //
1391                                 // DistributionPoint ::= SEQUENCE {
1392                                 //     distributionPoint       [0]     DistributionPointName OPTIONAL,
1393                                 //     reasons                 [1]     ReasonFlags OPTIONAL,
1394                                 //     cRLIssuer               [2]     GeneralNames OPTIONAL }
1395                                 //
1396                                 // DistributionPointName ::= CHOICE {
1397                                 //     fullName                [0]     GeneralNames,
1398                                 //     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
1399
1400                                 var cdp []distributionPoint
1401                                 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1402                                         return nil, err
1403                                 } else if len(rest) != 0 {
1404                                         return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1405                                 }
1406
1407                                 for _, dp := range cdp {
1408                                         // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1409                                         if len(dp.DistributionPoint.FullName) == 0 {
1410                                                 continue
1411                                         }
1412
1413                                         for _, fullName := range dp.DistributionPoint.FullName {
1414                                                 if fullName.Tag == 6 {
1415                                                         out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1416                                                 }
1417                                         }
1418                                 }
1419
1420                         case 35:
1421                                 // RFC 5280, 4.2.1.1
1422                                 var a authKeyId
1423                                 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1424                                         return nil, err
1425                                 } else if len(rest) != 0 {
1426                                         return nil, errors.New("x509: trailing data after X.509 authority key-id")
1427                                 }
1428                                 out.AuthorityKeyId = a.Id
1429
1430                         case 37:
1431                                 // RFC 5280, 4.2.1.12.  Extended Key Usage
1432
1433                                 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1434                                 //
1435                                 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1436                                 //
1437                                 // KeyPurposeId ::= OBJECT IDENTIFIER
1438
1439                                 var keyUsage []asn1.ObjectIdentifier
1440                                 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1441                                         return nil, err
1442                                 } else if len(rest) != 0 {
1443                                         return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1444                                 }
1445
1446                                 for _, u := range keyUsage {
1447                                         if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1448                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1449                                         } else {
1450                                                 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1451                                         }
1452                                 }
1453
1454                         case 14:
1455                                 // RFC 5280, 4.2.1.2
1456                                 var keyid []byte
1457                                 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1458                                         return nil, err
1459                                 } else if len(rest) != 0 {
1460                                         return nil, errors.New("x509: trailing data after X.509 key-id")
1461                                 }
1462                                 out.SubjectKeyId = keyid
1463
1464                         case 32:
1465                                 // RFC 5280 4.2.1.4: Certificate Policies
1466                                 var policies []policyInformation
1467                                 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1468                                         return nil, err
1469                                 } else if len(rest) != 0 {
1470                                         return nil, errors.New("x509: trailing data after X.509 certificate policies")
1471                                 }
1472                                 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1473                                 for i, policy := range policies {
1474                                         out.PolicyIdentifiers[i] = policy.Policy
1475                                 }
1476
1477                         default:
1478                                 // Unknown extensions are recorded if critical.
1479                                 unhandled = true
1480                         }
1481                 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1482                         // RFC 5280 4.2.2.1: Authority Information Access
1483                         var aia []authorityInfoAccess
1484                         if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1485                                 return nil, err
1486                         } else if len(rest) != 0 {
1487                                 return nil, errors.New("x509: trailing data after X.509 authority information")
1488                         }
1489
1490                         for _, v := range aia {
1491                                 // GeneralName: uniformResourceIdentifier [6] IA5String
1492                                 if v.Location.Tag != 6 {
1493                                         continue
1494                                 }
1495                                 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1496                                         out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1497                                 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1498                                         out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1499                                 }
1500                         }
1501                 } else {
1502                         // Unknown extensions are recorded if critical.
1503                         unhandled = true
1504                 }
1505
1506                 if e.Critical && unhandled {
1507                         out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1508                 }
1509         }
1510
1511         return out, nil
1512 }
1513
1514 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1515 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1516         var cert certificate
1517         rest, err := asn1.Unmarshal(asn1Data, &cert)
1518         if err != nil {
1519                 return nil, err
1520         }
1521         if len(rest) > 0 {
1522                 return nil, asn1.SyntaxError{Msg: "trailing data"}
1523         }
1524
1525         return parseCertificate(&cert)
1526 }
1527
1528 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1529 // data. The certificates must be concatenated with no intermediate padding.
1530 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1531         var v []*certificate
1532
1533         for len(asn1Data) > 0 {
1534                 cert := new(certificate)
1535                 var err error
1536                 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1537                 if err != nil {
1538                         return nil, err
1539                 }
1540                 v = append(v, cert)
1541         }
1542
1543         ret := make([]*Certificate, len(v))
1544         for i, ci := range v {
1545                 cert, err := parseCertificate(ci)
1546                 if err != nil {
1547                         return nil, err
1548                 }
1549                 ret[i] = cert
1550         }
1551
1552         return ret, nil
1553 }
1554
1555 func reverseBitsInAByte(in byte) byte {
1556         b1 := in>>4 | in<<4
1557         b2 := b1>>2&0x33 | b1<<2&0xcc
1558         b3 := b2>>1&0x55 | b2<<1&0xaa
1559         return b3
1560 }
1561
1562 // asn1BitLength returns the bit-length of bitString by considering the
1563 // most-significant bit in a byte to be the "first" bit. This convention
1564 // matches ASN.1, but differs from almost everything else.
1565 func asn1BitLength(bitString []byte) int {
1566         bitLen := len(bitString) * 8
1567
1568         for i := range bitString {
1569                 b := bitString[len(bitString)-i-1]
1570
1571                 for bit := uint(0); bit < 8; bit++ {
1572                         if (b>>bit)&1 == 1 {
1573                                 return bitLen
1574                         }
1575                         bitLen--
1576                 }
1577         }
1578
1579         return 0
1580 }
1581
1582 var (
1583         oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
1584         oidExtensionKeyUsage              = []int{2, 5, 29, 15}
1585         oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
1586         oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
1587         oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
1588         oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
1589         oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
1590         oidExtensionNameConstraints       = []int{2, 5, 29, 30}
1591         oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1592         oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1593         oidExtensionCRLNumber             = []int{2, 5, 29, 20}
1594 )
1595
1596 var (
1597         oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1598         oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1599 )
1600
1601 // oidNotInExtensions reports whether an extension with the given oid exists in
1602 // extensions.
1603 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1604         for _, e := range extensions {
1605                 if e.Id.Equal(oid) {
1606                         return true
1607                 }
1608         }
1609         return false
1610 }
1611
1612 // marshalSANs marshals a list of addresses into a the contents of an X.509
1613 // SubjectAlternativeName extension.
1614 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1615         var rawValues []asn1.RawValue
1616         for _, name := range dnsNames {
1617                 if err := isIA5String(name); err != nil {
1618                         return nil, err
1619                 }
1620                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1621         }
1622         for _, email := range emailAddresses {
1623                 if err := isIA5String(email); err != nil {
1624                         return nil, err
1625                 }
1626                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1627         }
1628         for _, rawIP := range ipAddresses {
1629                 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1630                 ip := rawIP.To4()
1631                 if ip == nil {
1632                         ip = rawIP
1633                 }
1634                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1635         }
1636         for _, uri := range uris {
1637                 uriStr := uri.String()
1638                 if err := isIA5String(uriStr); err != nil {
1639                         return nil, err
1640                 }
1641                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1642         }
1643         return asn1.Marshal(rawValues)
1644 }
1645
1646 func isIA5String(s string) error {
1647         for _, r := range s {
1648                 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1649                 if r > unicode.MaxASCII {
1650                         return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1651                 }
1652         }
1653
1654         return nil
1655 }
1656
1657 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1658         ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1659         n := 0
1660
1661         if template.KeyUsage != 0 &&
1662                 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1663                 ret[n].Id = oidExtensionKeyUsage
1664                 ret[n].Critical = true
1665
1666                 var a [2]byte
1667                 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1668                 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1669
1670                 l := 1
1671                 if a[1] != 0 {
1672                         l = 2
1673                 }
1674
1675                 bitString := a[:l]
1676                 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1677                 if err != nil {
1678                         return
1679                 }
1680                 n++
1681         }
1682
1683         if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1684                 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1685                 ret[n].Id = oidExtensionExtendedKeyUsage
1686
1687                 var oids []asn1.ObjectIdentifier
1688                 for _, u := range template.ExtKeyUsage {
1689                         if oid, ok := oidFromExtKeyUsage(u); ok {
1690                                 oids = append(oids, oid)
1691                         } else {
1692                                 err = errors.New("x509: unknown extended key usage")
1693                                 return
1694                         }
1695                 }
1696
1697                 oids = append(oids, template.UnknownExtKeyUsage...)
1698
1699                 ret[n].Value, err = asn1.Marshal(oids)
1700                 if err != nil {
1701                         return
1702                 }
1703                 n++
1704         }
1705
1706         if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1707                 // Leaving MaxPathLen as zero indicates that no maximum path
1708                 // length is desired, unless MaxPathLenZero is set. A value of
1709                 // -1 causes encoding/asn1 to omit the value as desired.
1710                 maxPathLen := template.MaxPathLen
1711                 if maxPathLen == 0 && !template.MaxPathLenZero {
1712                         maxPathLen = -1
1713                 }
1714                 ret[n].Id = oidExtensionBasicConstraints
1715                 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1716                 ret[n].Critical = true
1717                 if err != nil {
1718                         return
1719                 }
1720                 n++
1721         }
1722
1723         if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1724                 ret[n].Id = oidExtensionSubjectKeyId
1725                 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1726                 if err != nil {
1727                         return
1728                 }
1729                 n++
1730         }
1731
1732         if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1733                 ret[n].Id = oidExtensionAuthorityKeyId
1734                 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1735                 if err != nil {
1736                         return
1737                 }
1738                 n++
1739         }
1740
1741         if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1742                 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1743                 ret[n].Id = oidExtensionAuthorityInfoAccess
1744                 var aiaValues []authorityInfoAccess
1745                 for _, name := range template.OCSPServer {
1746                         aiaValues = append(aiaValues, authorityInfoAccess{
1747                                 Method:   oidAuthorityInfoAccessOcsp,
1748                                 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1749                         })
1750                 }
1751                 for _, name := range template.IssuingCertificateURL {
1752                         aiaValues = append(aiaValues, authorityInfoAccess{
1753                                 Method:   oidAuthorityInfoAccessIssuers,
1754                                 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1755                         })
1756                 }
1757                 ret[n].Value, err = asn1.Marshal(aiaValues)
1758                 if err != nil {
1759                         return
1760                 }
1761                 n++
1762         }
1763
1764         if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1765                 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1766                 ret[n].Id = oidExtensionSubjectAltName
1767                 // From RFC 5280, Section 4.2.1.6:
1768                 // “If the subject field contains an empty sequence ... then
1769                 // subjectAltName extension ... is marked as critical”
1770                 ret[n].Critical = subjectIsEmpty
1771                 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1772                 if err != nil {
1773                         return
1774                 }
1775                 n++
1776         }
1777
1778         if len(template.PolicyIdentifiers) > 0 &&
1779                 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1780                 ret[n].Id = oidExtensionCertificatePolicies
1781                 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1782                 for i, policy := range template.PolicyIdentifiers {
1783                         policies[i].Policy = policy
1784                 }
1785                 ret[n].Value, err = asn1.Marshal(policies)
1786                 if err != nil {
1787                         return
1788                 }
1789                 n++
1790         }
1791
1792         if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1793                 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1794                 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1795                 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1796                 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1797                 ret[n].Id = oidExtensionNameConstraints
1798                 ret[n].Critical = template.PermittedDNSDomainsCritical
1799
1800                 ipAndMask := func(ipNet *net.IPNet) []byte {
1801                         maskedIP := ipNet.IP.Mask(ipNet.Mask)
1802                         ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1803                         ipAndMask = append(ipAndMask, maskedIP...)
1804                         ipAndMask = append(ipAndMask, ipNet.Mask...)
1805                         return ipAndMask
1806                 }
1807
1808                 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1809                         var b cryptobyte.Builder
1810
1811                         for _, name := range dns {
1812                                 if err = isIA5String(name); err != nil {
1813                                         return nil, err
1814                                 }
1815
1816                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1817                                         b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1818                                                 b.AddBytes([]byte(name))
1819                                         })
1820                                 })
1821                         }
1822
1823                         for _, ipNet := range ips {
1824                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1825                                         b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1826                                                 b.AddBytes(ipAndMask(ipNet))
1827                                         })
1828                                 })
1829                         }
1830
1831                         for _, email := range emails {
1832                                 if err = isIA5String(email); err != nil {
1833                                         return nil, err
1834                                 }
1835
1836                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1837                                         b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1838                                                 b.AddBytes([]byte(email))
1839                                         })
1840                                 })
1841                         }
1842
1843                         for _, uriDomain := range uriDomains {
1844                                 if err = isIA5String(uriDomain); err != nil {
1845                                         return nil, err
1846                                 }
1847
1848                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1849                                         b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1850                                                 b.AddBytes([]byte(uriDomain))
1851                                         })
1852                                 })
1853                         }
1854
1855                         return b.Bytes()
1856                 }
1857
1858                 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1859                 if err != nil {
1860                         return nil, err
1861                 }
1862
1863                 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1864                 if err != nil {
1865                         return nil, err
1866                 }
1867
1868                 var b cryptobyte.Builder
1869                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1870                         if len(permitted) > 0 {
1871                                 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1872                                         b.AddBytes(permitted)
1873                                 })
1874                         }
1875
1876                         if len(excluded) > 0 {
1877                                 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1878                                         b.AddBytes(excluded)
1879                                 })
1880                         }
1881                 })
1882
1883                 ret[n].Value, err = b.Bytes()
1884                 if err != nil {
1885                         return nil, err
1886                 }
1887                 n++
1888         }
1889
1890         if len(template.CRLDistributionPoints) > 0 &&
1891                 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1892                 ret[n].Id = oidExtensionCRLDistributionPoints
1893
1894                 var crlDp []distributionPoint
1895                 for _, name := range template.CRLDistributionPoints {
1896                         dp := distributionPoint{
1897                                 DistributionPoint: distributionPointName{
1898                                         FullName: []asn1.RawValue{
1899                                                 {Tag: 6, Class: 2, Bytes: []byte(name)},
1900                                         },
1901                                 },
1902                         }
1903                         crlDp = append(crlDp, dp)
1904                 }
1905
1906                 ret[n].Value, err = asn1.Marshal(crlDp)
1907                 if err != nil {
1908                         return
1909                 }
1910                 n++
1911         }
1912
1913         // Adding another extension here? Remember to update the maximum number
1914         // of elements in the make() at the top of the function and the list of
1915         // template fields used in CreateCertificate documentation.
1916
1917         return append(ret[:n], template.ExtraExtensions...), nil
1918 }
1919
1920 func subjectBytes(cert *Certificate) ([]byte, error) {
1921         if len(cert.RawSubject) > 0 {
1922                 return cert.RawSubject, nil
1923         }
1924
1925         return asn1.Marshal(cert.Subject.ToRDNSequence())
1926 }
1927
1928 // signingParamsForPublicKey returns the parameters to use for signing with
1929 // priv. If requestedSigAlgo is not zero then it overrides the default
1930 // signature algorithm.
1931 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1932         var pubType PublicKeyAlgorithm
1933
1934         switch pub := pub.(type) {
1935         case *rsa.PublicKey:
1936                 pubType = RSA
1937                 hashFunc = crypto.SHA256
1938                 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1939                 sigAlgo.Parameters = asn1.NullRawValue
1940
1941         case *ecdsa.PublicKey:
1942                 pubType = ECDSA
1943
1944                 switch pub.Curve {
1945                 case elliptic.P224(), elliptic.P256():
1946                         hashFunc = crypto.SHA256
1947                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1948                 case elliptic.P384():
1949                         hashFunc = crypto.SHA384
1950                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1951                 case elliptic.P521():
1952                         hashFunc = crypto.SHA512
1953                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1954                 default:
1955                         err = errors.New("x509: unknown elliptic curve")
1956                 }
1957
1958         case ed25519.PublicKey:
1959                 pubType = Ed25519
1960                 sigAlgo.Algorithm = oidSignatureEd25519
1961
1962         default:
1963                 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1964         }
1965
1966         if err != nil {
1967                 return
1968         }
1969
1970         if requestedSigAlgo == 0 {
1971                 return
1972         }
1973
1974         found := false
1975         for _, details := range signatureAlgorithmDetails {
1976                 if details.algo == requestedSigAlgo {
1977                         if details.pubKeyAlgo != pubType {
1978                                 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1979                                 return
1980                         }
1981                         sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1982                         if hashFunc == 0 && pubType != Ed25519 {
1983                                 err = errors.New("x509: cannot sign with hash function requested")
1984                                 return
1985                         }
1986                         if requestedSigAlgo.isRSAPSS() {
1987                                 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1988                         }
1989                         found = true
1990                         break
1991                 }
1992         }
1993
1994         if !found {
1995                 err = errors.New("x509: unknown SignatureAlgorithm")
1996         }
1997
1998         return
1999 }
2000
2001 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2002 // just an empty SEQUENCE.
2003 var emptyASN1Subject = []byte{0x30, 0}
2004
2005 // CreateCertificate creates a new X.509v3 certificate based on a template.
2006 // The following members of template are used:
2007 //
2008 //  - AuthorityKeyId
2009 //  - BasicConstraintsValid
2010 //  - CRLDistributionPoints
2011 //  - DNSNames
2012 //  - EmailAddresses
2013 //  - ExcludedDNSDomains
2014 //  - ExcludedEmailAddresses
2015 //  - ExcludedIPRanges
2016 //  - ExcludedURIDomains
2017 //  - ExtKeyUsage
2018 //  - ExtraExtensions
2019 //  - IPAddresses
2020 //  - IsCA
2021 //  - IssuingCertificateURL
2022 //  - KeyUsage
2023 //  - MaxPathLen
2024 //  - MaxPathLenZero
2025 //  - NotAfter
2026 //  - NotBefore
2027 //  - OCSPServer
2028 //  - PermittedDNSDomains
2029 //  - PermittedDNSDomainsCritical
2030 //  - PermittedEmailAddresses
2031 //  - PermittedIPRanges
2032 //  - PermittedURIDomains
2033 //  - PolicyIdentifiers
2034 //  - SerialNumber
2035 //  - SignatureAlgorithm
2036 //  - Subject
2037 //  - SubjectKeyId
2038 //  - URIs
2039 //  - UnknownExtKeyUsage
2040 //
2041 // The certificate is signed by parent. If parent is equal to template then the
2042 // certificate is self-signed. The parameter pub is the public key of the
2043 // signee and priv is the private key of the signer.
2044 //
2045 // The returned slice is the certificate in DER encoding.
2046 //
2047 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2048 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2049 // crypto.Signer with a supported public key.
2050 //
2051 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2052 // unless the resulting certificate is self-signed. Otherwise the value from
2053 // template will be used.
2054 //
2055 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
2056 // will be generated from the hash of the public key.
2057 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2058         key, ok := priv.(crypto.Signer)
2059         if !ok {
2060                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2061         }
2062
2063         if template.SerialNumber == nil {
2064                 return nil, errors.New("x509: no SerialNumber given")
2065         }
2066
2067         if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
2068                 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
2069         }
2070
2071         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2072         if err != nil {
2073                 return nil, err
2074         }
2075
2076         publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2077         if err != nil {
2078                 return nil, err
2079         }
2080
2081         asn1Issuer, err := subjectBytes(parent)
2082         if err != nil {
2083                 return
2084         }
2085
2086         asn1Subject, err := subjectBytes(template)
2087         if err != nil {
2088                 return
2089         }
2090
2091         authorityKeyId := template.AuthorityKeyId
2092         if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2093                 authorityKeyId = parent.SubjectKeyId
2094         }
2095
2096         subjectKeyId := template.SubjectKeyId
2097         if len(subjectKeyId) == 0 && template.IsCA {
2098                 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
2099                 //   (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
2100                 //   value of the BIT STRING subjectPublicKey (excluding the tag,
2101                 //   length, and number of unused bits).
2102                 h := sha1.Sum(publicKeyBytes)
2103                 subjectKeyId = h[:]
2104         }
2105
2106         extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
2107         if err != nil {
2108                 return
2109         }
2110
2111         encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2112         c := tbsCertificate{
2113                 Version:            2,
2114                 SerialNumber:       template.SerialNumber,
2115                 SignatureAlgorithm: signatureAlgorithm,
2116                 Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
2117                 Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2118                 Subject:            asn1.RawValue{FullBytes: asn1Subject},
2119                 PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2120                 Extensions:         extensions,
2121         }
2122
2123         tbsCertContents, err := asn1.Marshal(c)
2124         if err != nil {
2125                 return
2126         }
2127         c.Raw = tbsCertContents
2128
2129         signed := tbsCertContents
2130         if hashFunc != 0 {
2131                 h := hashFunc.New()
2132                 h.Write(signed)
2133                 signed = h.Sum(nil)
2134         }
2135
2136         var signerOpts crypto.SignerOpts = hashFunc
2137         if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2138                 signerOpts = &rsa.PSSOptions{
2139                         SaltLength: rsa.PSSSaltLengthEqualsHash,
2140                         Hash:       hashFunc,
2141                 }
2142         }
2143
2144         var signature []byte
2145         signature, err = key.Sign(rand, signed, signerOpts)
2146         if err != nil {
2147                 return
2148         }
2149
2150         signedCert, err := asn1.Marshal(certificate{
2151                 nil,
2152                 c,
2153                 signatureAlgorithm,
2154                 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2155         })
2156         if err != nil {
2157                 return nil, err
2158         }
2159
2160         // Check the signature to ensure the crypto.Signer behaved correctly.
2161         // We skip this check if the signature algorithm is MD5WithRSA as we
2162         // only support this algorithm for signing, and not verification.
2163         if sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm); sigAlg != MD5WithRSA {
2164                 if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil {
2165                         return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
2166                 }
2167         }
2168
2169         return signedCert, nil
2170 }
2171
2172 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2173 // CRL.
2174 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2175
2176 // pemType is the type of a PEM encoded CRL.
2177 var pemType = "X509 CRL"
2178
2179 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2180 // encoded CRLs will appear where they should be DER encoded, so this function
2181 // will transparently handle PEM encoding as long as there isn't any leading
2182 // garbage.
2183 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2184         if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2185                 block, _ := pem.Decode(crlBytes)
2186                 if block != nil && block.Type == pemType {
2187                         crlBytes = block.Bytes
2188                 }
2189         }
2190         return ParseDERCRL(crlBytes)
2191 }
2192
2193 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2194 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2195         certList := new(pkix.CertificateList)
2196         if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2197                 return nil, err
2198         } else if len(rest) != 0 {
2199                 return nil, errors.New("x509: trailing data after CRL")
2200         }
2201         return certList, nil
2202 }
2203
2204 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2205 // contains the given list of revoked certificates.
2206 //
2207 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2208 // To generate a standards compliant CRL, use CreateRevocationList instead.
2209 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2210         key, ok := priv.(crypto.Signer)
2211         if !ok {
2212                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2213         }
2214
2215         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2216         if err != nil {
2217                 return nil, err
2218         }
2219
2220         // Force revocation times to UTC per RFC 5280.
2221         revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2222         for i, rc := range revokedCerts {
2223                 rc.RevocationTime = rc.RevocationTime.UTC()
2224                 revokedCertsUTC[i] = rc
2225         }
2226
2227         tbsCertList := pkix.TBSCertificateList{
2228                 Version:             1,
2229                 Signature:           signatureAlgorithm,
2230                 Issuer:              c.Subject.ToRDNSequence(),
2231                 ThisUpdate:          now.UTC(),
2232                 NextUpdate:          expiry.UTC(),
2233                 RevokedCertificates: revokedCertsUTC,
2234         }
2235
2236         // Authority Key Id
2237         if len(c.SubjectKeyId) > 0 {
2238                 var aki pkix.Extension
2239                 aki.Id = oidExtensionAuthorityKeyId
2240                 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2241                 if err != nil {
2242                         return
2243                 }
2244                 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2245         }
2246
2247         tbsCertListContents, err := asn1.Marshal(tbsCertList)
2248         if err != nil {
2249                 return
2250         }
2251
2252         signed := tbsCertListContents
2253         if hashFunc != 0 {
2254                 h := hashFunc.New()
2255                 h.Write(signed)
2256                 signed = h.Sum(nil)
2257         }
2258
2259         var signature []byte
2260         signature, err = key.Sign(rand, signed, hashFunc)
2261         if err != nil {
2262                 return
2263         }
2264
2265         return asn1.Marshal(pkix.CertificateList{
2266                 TBSCertList:        tbsCertList,
2267                 SignatureAlgorithm: signatureAlgorithm,
2268                 SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2269         })
2270 }
2271
2272 // CertificateRequest represents a PKCS #10, certificate signature request.
2273 type CertificateRequest struct {
2274         Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2275         RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2276         RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
2277         RawSubject               []byte // DER encoded Subject.
2278
2279         Version            int
2280         Signature          []byte
2281         SignatureAlgorithm SignatureAlgorithm
2282
2283         PublicKeyAlgorithm PublicKeyAlgorithm
2284         PublicKey          interface{}
2285
2286         Subject pkix.Name
2287
2288         // Attributes contains the CSR attributes that can parse as
2289         // pkix.AttributeTypeAndValueSET.
2290         //
2291         // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2292         // generating the requestedExtensions attribute.
2293         Attributes []pkix.AttributeTypeAndValueSET
2294
2295         // Extensions contains all requested extensions, in raw form. When parsing
2296         // CSRs, this can be used to extract extensions that are not parsed by this
2297         // package.
2298         Extensions []pkix.Extension
2299
2300         // ExtraExtensions contains extensions to be copied, raw, into any CSR
2301         // marshaled by CreateCertificateRequest. Values override any extensions
2302         // that would otherwise be produced based on the other fields but are
2303         // overridden by any extensions specified in Attributes.
2304         //
2305         // The ExtraExtensions field is not populated by ParseCertificateRequest,
2306         // see Extensions instead.
2307         ExtraExtensions []pkix.Extension
2308
2309         // Subject Alternate Name values.
2310         DNSNames       []string
2311         EmailAddresses []string
2312         IPAddresses    []net.IP
2313         URIs           []*url.URL
2314 }
2315
2316 // These structures reflect the ASN.1 structure of X.509 certificate
2317 // signature requests (see RFC 2986):
2318
2319 type tbsCertificateRequest struct {
2320         Raw           asn1.RawContent
2321         Version       int
2322         Subject       asn1.RawValue
2323         PublicKey     publicKeyInfo
2324         RawAttributes []asn1.RawValue `asn1:"tag:0"`
2325 }
2326
2327 type certificateRequest struct {
2328         Raw                asn1.RawContent
2329         TBSCSR             tbsCertificateRequest
2330         SignatureAlgorithm pkix.AlgorithmIdentifier
2331         SignatureValue     asn1.BitString
2332 }
2333
2334 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
2335 // extensions in a CSR.
2336 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2337
2338 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2339 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2340 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2341         var rawAttributes []asn1.RawValue
2342         b, err := asn1.Marshal(attributes)
2343         if err != nil {
2344                 return nil, err
2345         }
2346         rest, err := asn1.Unmarshal(b, &rawAttributes)
2347         if err != nil {
2348                 return nil, err
2349         }
2350         if len(rest) != 0 {
2351                 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2352         }
2353         return rawAttributes, nil
2354 }
2355
2356 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2357 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2358         var attributes []pkix.AttributeTypeAndValueSET
2359         for _, rawAttr := range rawAttributes {
2360                 var attr pkix.AttributeTypeAndValueSET
2361                 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2362                 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2363                 // (i.e.: challengePassword or unstructuredName).
2364                 if err == nil && len(rest) == 0 {
2365                         attributes = append(attributes, attr)
2366                 }
2367         }
2368         return attributes
2369 }
2370
2371 // parseCSRExtensions parses the attributes from a CSR and extracts any
2372 // requested extensions.
2373 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2374         // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2375         type pkcs10Attribute struct {
2376                 Id     asn1.ObjectIdentifier
2377                 Values []asn1.RawValue `asn1:"set"`
2378         }
2379
2380         var ret []pkix.Extension
2381         for _, rawAttr := range rawAttributes {
2382                 var attr pkcs10Attribute
2383                 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2384                         // Ignore attributes that don't parse.
2385                         continue
2386                 }
2387
2388                 if !attr.Id.Equal(oidExtensionRequest) {
2389                         continue
2390                 }
2391
2392                 var extensions []pkix.Extension
2393                 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2394                         return nil, err
2395                 }
2396                 ret = append(ret, extensions...)
2397         }
2398
2399         return ret, nil
2400 }
2401
2402 // CreateCertificateRequest creates a new certificate request based on a
2403 // template. The following members of template are used:
2404 //
2405 //  - SignatureAlgorithm
2406 //  - Subject
2407 //  - DNSNames
2408 //  - EmailAddresses
2409 //  - IPAddresses
2410 //  - URIs
2411 //  - ExtraExtensions
2412 //  - Attributes (deprecated)
2413 //
2414 // priv is the private key to sign the CSR with, and the corresponding public
2415 // key will be included in the CSR. It must implement crypto.Signer and its
2416 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2417 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2418 // ed25519.PrivateKey satisfies this.)
2419 //
2420 // The returned slice is the certificate request in DER encoding.
2421 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2422         key, ok := priv.(crypto.Signer)
2423         if !ok {
2424                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2425         }
2426
2427         var hashFunc crypto.Hash
2428         var sigAlgo pkix.AlgorithmIdentifier
2429         hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2430         if err != nil {
2431                 return nil, err
2432         }
2433
2434         var publicKeyBytes []byte
2435         var publicKeyAlgorithm pkix.AlgorithmIdentifier
2436         publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2437         if err != nil {
2438                 return nil, err
2439         }
2440
2441         var extensions []pkix.Extension
2442
2443         if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2444                 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2445                 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2446                 if err != nil {
2447                         return nil, err
2448                 }
2449
2450                 extensions = append(extensions, pkix.Extension{
2451                         Id:    oidExtensionSubjectAltName,
2452                         Value: sanBytes,
2453                 })
2454         }
2455
2456         extensions = append(extensions, template.ExtraExtensions...)
2457
2458         // Make a copy of template.Attributes because we may alter it below.
2459         attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2460         for _, attr := range template.Attributes {
2461                 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2462                 copy(values, attr.Value)
2463                 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2464                         Type:  attr.Type,
2465                         Value: values,
2466                 })
2467         }
2468
2469         extensionsAppended := false
2470         if len(extensions) > 0 {
2471                 // Append the extensions to an existing attribute if possible.
2472                 for _, atvSet := range attributes {
2473                         if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2474                                 continue
2475                         }
2476
2477                         // specifiedExtensions contains all the extensions that we
2478                         // found specified via template.Attributes.
2479                         specifiedExtensions := make(map[string]bool)
2480
2481                         for _, atvs := range atvSet.Value {
2482                                 for _, atv := range atvs {
2483                                         specifiedExtensions[atv.Type.String()] = true
2484                                 }
2485                         }
2486
2487                         newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2488                         newValue = append(newValue, atvSet.Value[0]...)
2489
2490                         for _, e := range extensions {
2491                                 if specifiedExtensions[e.Id.String()] {
2492                                         // Attributes already contained a value for
2493                                         // this extension and it takes priority.
2494                                         continue
2495                                 }
2496
2497                                 newValue = append(newValue, pkix.AttributeTypeAndValue{
2498                                         // There is no place for the critical
2499                                         // flag in an AttributeTypeAndValue.
2500                                         Type:  e.Id,
2501                                         Value: e.Value,
2502                                 })
2503                         }
2504
2505                         atvSet.Value[0] = newValue
2506                         extensionsAppended = true
2507                         break
2508                 }
2509         }
2510
2511         rawAttributes, err := newRawAttributes(attributes)
2512         if err != nil {
2513                 return
2514         }
2515
2516         // If not included in attributes, add a new attribute for the
2517         // extensions.
2518         if len(extensions) > 0 && !extensionsAppended {
2519                 attr := struct {
2520                         Type  asn1.ObjectIdentifier
2521                         Value [][]pkix.Extension `asn1:"set"`
2522                 }{
2523                         Type:  oidExtensionRequest,
2524                         Value: [][]pkix.Extension{extensions},
2525                 }
2526
2527                 b, err := asn1.Marshal(attr)
2528                 if err != nil {
2529                         return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2530                 }
2531
2532                 var rawValue asn1.RawValue
2533                 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2534                         return nil, err
2535                 }
2536
2537                 rawAttributes = append(rawAttributes, rawValue)
2538         }
2539
2540         asn1Subject := template.RawSubject
2541         if len(asn1Subject) == 0 {
2542                 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2543                 if err != nil {
2544                         return nil, err
2545                 }
2546         }
2547
2548         tbsCSR := tbsCertificateRequest{
2549                 Version: 0, // PKCS #10, RFC 2986
2550                 Subject: asn1.RawValue{FullBytes: asn1Subject},
2551                 PublicKey: publicKeyInfo{
2552                         Algorithm: publicKeyAlgorithm,
2553                         PublicKey: asn1.BitString{
2554                                 Bytes:     publicKeyBytes,
2555                                 BitLength: len(publicKeyBytes) * 8,
2556                         },
2557                 },
2558                 RawAttributes: rawAttributes,
2559         }
2560
2561         tbsCSRContents, err := asn1.Marshal(tbsCSR)
2562         if err != nil {
2563                 return
2564         }
2565         tbsCSR.Raw = tbsCSRContents
2566
2567         signed := tbsCSRContents
2568         if hashFunc != 0 {
2569                 h := hashFunc.New()
2570                 h.Write(signed)
2571                 signed = h.Sum(nil)
2572         }
2573
2574         var signature []byte
2575         signature, err = key.Sign(rand, signed, hashFunc)
2576         if err != nil {
2577                 return
2578         }
2579
2580         return asn1.Marshal(certificateRequest{
2581                 TBSCSR:             tbsCSR,
2582                 SignatureAlgorithm: sigAlgo,
2583                 SignatureValue: asn1.BitString{
2584                         Bytes:     signature,
2585                         BitLength: len(signature) * 8,
2586                 },
2587         })
2588 }
2589
2590 // ParseCertificateRequest parses a single certificate request from the
2591 // given ASN.1 DER data.
2592 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2593         var csr certificateRequest
2594
2595         rest, err := asn1.Unmarshal(asn1Data, &csr)
2596         if err != nil {
2597                 return nil, err
2598         } else if len(rest) != 0 {
2599                 return nil, asn1.SyntaxError{Msg: "trailing data"}
2600         }
2601
2602         return parseCertificateRequest(&csr)
2603 }
2604
2605 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2606         out := &CertificateRequest{
2607                 Raw:                      in.Raw,
2608                 RawTBSCertificateRequest: in.TBSCSR.Raw,
2609                 RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
2610                 RawSubject:               in.TBSCSR.Subject.FullBytes,
2611
2612                 Signature:          in.SignatureValue.RightAlign(),
2613                 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2614
2615                 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2616
2617                 Version:    in.TBSCSR.Version,
2618                 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2619         }
2620
2621         var err error
2622         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2623         if err != nil {
2624                 return nil, err
2625         }
2626
2627         var subject pkix.RDNSequence
2628         if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2629                 return nil, err
2630         } else if len(rest) != 0 {
2631                 return nil, errors.New("x509: trailing data after X.509 Subject")
2632         }
2633
2634         out.Subject.FillFromRDNSequence(&subject)
2635
2636         if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2637                 return nil, err
2638         }
2639
2640         for _, extension := range out.Extensions {
2641                 if extension.Id.Equal(oidExtensionSubjectAltName) {
2642                         out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2643                         if err != nil {
2644                                 return nil, err
2645                         }
2646                 }
2647         }
2648
2649         return out, nil
2650 }
2651
2652 // CheckSignature reports whether the signature on c is valid.
2653 func (c *CertificateRequest) CheckSignature() error {
2654         return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2655 }
2656
2657 // RevocationList contains the fields used to create an X.509 v2 Certificate
2658 // Revocation list with CreateRevocationList.
2659 type RevocationList struct {
2660         // SignatureAlgorithm is used to determine the signature algorithm to be
2661         // used when signing the CRL. If 0 the default algorithm for the signing
2662         // key will be used.
2663         SignatureAlgorithm SignatureAlgorithm
2664
2665         // RevokedCertificates is used to populate the revokedCertificates
2666         // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2667         // in which case an empty CRL will be created.
2668         RevokedCertificates []pkix.RevokedCertificate
2669
2670         // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2671         // which should be a monotonically increasing sequence number for a given
2672         // CRL scope and CRL issuer.
2673         Number *big.Int
2674         // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2675         // indicates the issuance date of the CRL.
2676         ThisUpdate time.Time
2677         // NextUpdate is used to populate the nextUpdate field in the CRL, which
2678         // indicates the date by which the next CRL will be issued. NextUpdate
2679         // must be greater than ThisUpdate.
2680         NextUpdate time.Time
2681         // ExtraExtensions contains any additional extensions to add directly to
2682         // the CRL.
2683         ExtraExtensions []pkix.Extension
2684 }
2685
2686 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2687 // according to RFC 5280, based on template.
2688 //
2689 // The CRL is signed by priv which should be the private key associated with
2690 // the public key in the issuer certificate.
2691 //
2692 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2693 // order to use it as a CRL issuer.
2694 //
2695 // The issuer distinguished name CRL field and authority key identifier
2696 // extension are populated using the issuer certificate. issuer must have
2697 // SubjectKeyId set.
2698 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2699         if template == nil {
2700                 return nil, errors.New("x509: template can not be nil")
2701         }
2702         if issuer == nil {
2703                 return nil, errors.New("x509: issuer can not be nil")
2704         }
2705         if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2706                 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2707         }
2708         if len(issuer.SubjectKeyId) == 0 {
2709                 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2710         }
2711         if template.NextUpdate.Before(template.ThisUpdate) {
2712                 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2713         }
2714         if template.Number == nil {
2715                 return nil, errors.New("x509: template contains nil Number field")
2716         }
2717
2718         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2719         if err != nil {
2720                 return nil, err
2721         }
2722
2723         // Force revocation times to UTC per RFC 5280.
2724         revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2725         for i, rc := range template.RevokedCertificates {
2726                 rc.RevocationTime = rc.RevocationTime.UTC()
2727                 revokedCertsUTC[i] = rc
2728         }
2729
2730         aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2731         if err != nil {
2732                 return nil, err
2733         }
2734         crlNum, err := asn1.Marshal(template.Number)
2735         if err != nil {
2736                 return nil, err
2737         }
2738
2739         tbsCertList := pkix.TBSCertificateList{
2740                 Version:    1, // v2
2741                 Signature:  signatureAlgorithm,
2742                 Issuer:     issuer.Subject.ToRDNSequence(),
2743                 ThisUpdate: template.ThisUpdate.UTC(),
2744                 NextUpdate: template.NextUpdate.UTC(),
2745                 Extensions: []pkix.Extension{
2746                         {
2747                                 Id:    oidExtensionAuthorityKeyId,
2748                                 Value: aki,
2749                         },
2750                         {
2751                                 Id:    oidExtensionCRLNumber,
2752                                 Value: crlNum,
2753                         },
2754                 },
2755         }
2756         if len(revokedCertsUTC) > 0 {
2757                 tbsCertList.RevokedCertificates = revokedCertsUTC
2758         }
2759
2760         if len(template.ExtraExtensions) > 0 {
2761                 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2762         }
2763
2764         tbsCertListContents, err := asn1.Marshal(tbsCertList)
2765         if err != nil {
2766                 return nil, err
2767         }
2768
2769         input := tbsCertListContents
2770         if hashFunc != 0 {
2771                 h := hashFunc.New()
2772                 h.Write(tbsCertListContents)
2773                 input = h.Sum(nil)
2774         }
2775         var signerOpts crypto.SignerOpts = hashFunc
2776         if template.SignatureAlgorithm.isRSAPSS() {
2777                 signerOpts = &rsa.PSSOptions{
2778                         SaltLength: rsa.PSSSaltLengthEqualsHash,
2779                         Hash:       hashFunc,
2780                 }
2781         }
2782
2783         signature, err := priv.Sign(rand, input, signerOpts)
2784         if err != nil {
2785                 return nil, err
2786         }
2787
2788         return asn1.Marshal(pkix.CertificateList{
2789                 TBSCertList:        tbsCertList,
2790                 SignatureAlgorithm: signatureAlgorithm,
2791                 SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2792         })
2793 }