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