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