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