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