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